摘自:

/**/ 
  /*说明:了解Linux下进程和进程间通过管道通信
* 功能:统计2个文本文件的字数和,2个参数分别为两文件名
* 描述:父进程启动,开启子进程,子进程统计一个文本的字数,
*         待子进程结束,父进程统计另一个,在父进程中计算和打印统计结果
*/ 
  
#include  
  < 
  unistd.h 
  > 
  
#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!! ");
    else
        printf("Input a file two file names to count their total words!! ");

    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 ",num1);
        printf("There are %d words in file2 ",num2);
        printf("There are %d words in total ",totalnum);
        exit(1);
    }
    //关闭文件
    fclose(fpin1);
    fclose(fpin2);
    return 0;
} 
  

 
  // 
  文件字数统计函数 
  
 
  int 
   count(FILE 
  * 
   fpin)
 
  ... 
  {
    // 略...
    return 0;
}


说明:


* 调用两次count()就可完成任务,不必fork子进程,所以本例仅仅用来演示管道通信。


* fork()返回子进程进程号PID,0表示为父进程,在此处进程执行一般分叉为两部份,分别是父进程与子进程。


* pipe()创建了一个管道,一对文件描述符分别表示输入 与输出。