多进程小例子--fork+pipe

 1 #include<stdio.h>
  2 #include<unistd.h>
  3
  4 #define m 6
  5 int main()
  6 {
  7         int pipefd[2];
  8         int pid;
  9         int m1;
 10
 11         if(pipe(pipefd)<0)
 12         {
 13                 printf("unable to create pipe!\n");
 14                 return 1;
 15         }
 16         pid=fork();
 17         if(pid>0)    //parent
 18         {
 19                 m1=m;
 20                 close(pipefd[0]);  //close read end
 21                 write(pipefd[1],&m1,sizeof(int)); //read m1
 22                 wait(NULL);  // wait for child complete
 23                 close(pipefd[1]);
 24         }
 25         else if(pid==0)
 26         {
 27                 close(pipefd[1]);
 28                 read(pipefd[0],&m1,sizeof(int));  //read m1
 29                 while(m1>0)
 30                 {
 31                         printf("hello world!\n");
 32                         m1--;
 33                 }
 34                 close(pipefd[0]);
 35         }
 36         else
 37         {
 38                 printf("unable to firk!\n");
 39                 return 1;
 40         }
 41         return 0;
 42 }

posted on 2013-07-06 23:21  hrbust_09zhangyabin  阅读(264)  评论(0编辑  收藏  举报