Linux下进程间管道通信小作业

来源:互联网 发布:Linux系统备份软件 编辑:程序博客网 时间:2024/05/21 22:36
 /*说明:一次作业,目的是了解Linux下进程和进程间通过管道通信
*        没考虑复杂算法和其他一些可能出现的问题
*功能:统计2个文本文件的字数和,2个参数分别为两文件名
*描述:父进程启动,开启子进程,子进程统计一个文本的字数,
*        待子进程结束,父进程统计另一个,在父进程中计算和打印统计结果
*/
#include <unistd.h
>
#include <stdio.h>
#include <stdlib.h>

int count(FILE*);
int main(int argcchar *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(FILEfpin)
{
    
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