linux管道生产大于消费,Linux下进程间管道通信小作业

本文介绍了一个简单的Linux程序示例,该程序利用进程和管道实现两个文本文件的字数统计。父进程创建子进程,子进程统计一个文件的字数并通过管道将结果传回给父进程;父进程完成另一个文件的统计,并最终输出两个文件的字数总和。

/*说明:一次作业,目的是了解Linux下进程和进程间通过管道通信

*        没考虑复杂算法和其他一些可能出现的问题

*功能:统计2个文本文件的字数和,2个参数分别为两文件名

*描述:父进程启动,开启子进程,子进程统计一个文本的字数,

*        待子进程结束,父进程统计另一个,在父进程中计算和打印统计结果

*/

#include 

#include  < stdio . h >

#include  < stdlib . h >

int  count ( FILE *);

int  main ( int  argc ,  char  * argv [])

{

int  num1 , num2 , totalnum ;     //文件1,文件2,中的字数和总字数

FILE  * fpin1 ,* fpin2 ;  //两个文件指针

if ( argc == 3 )

{

fpin1 = fopen ( argv [ 1 ], "r" );

fpin2 = fopen ( argv [ 2 ], "r" );

}

else if ( argc > 3 )

printf ( "Too many args!!/n" );

else

printf ( "Input a file two file names to count their total words!!/n" );

pid_t child ;

int  status ;

int  fds [ 2 ];

int  buf1 [ 1 ], buf2 [ 1 ];

pipe ( fds );   //开启管道

if (( child = fork ())==- 1 )

{

perror ( "fork" );

exit ( EXIT_FAILURE );

}

else if  ( child == 0 )  //子进程

{

close ( fds [ 0 ]);

buf1 [ 0 ]= count ( fpin1 );

write ( fds [ 1 ], buf1 , sizeof ( int ));     //结果写入管道

exit ( 1 );

}

else  //父进程

{

wait ( 0 );   //等待子进程结束

read ( fds [ 0 ], buf2 , sizeof ( int ));  //从管道中读子进程返回结果

num1 = buf2 [ 0 ];

num2 = count ( fpin2 );

totalnum = num1 + num2 ;

printf ( "There are %d words in file1/n" , num1 );

printf ( "There are %d words in file2/n" , num2 );

printf ( "There are %d words in total/n" , totalnum );

exit ( 1 );

}

//关闭文件

fclose ( fpin1 );

fclose ( fpin2 );

return  0 ;

}

//文件字数统计函数

int  count ( FILE *  fpin )

{

int  num = 0 ;

char  ch ;

int  start = 0 ;  //字是否开始

int  end = 0 ;      //字是否结束

while (! feof ( fpin ))

{

ch = getc ( fpin );

if (( ch >= 65 && ch <= 90 )||( ch >= 97 && ch <= 122 ))  //字以字母开头

start = 1 ;

if ( ch == 10 || ch == 13 || ch == 9 || ch == 32 )   //字以换行,回车,指标符,空格结束

end = 1 ;

if ( start == 1 && end == 1 )  //字开始并结束了字数加1

{

num ++;

start = 0 ;  //清0准备下一个统计

end = 0 ;

}

}

return  num ;

}

Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=1607259

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值