pipe()

来源:互联网 发布:使命召唤ol 知乎 编辑:程序博客网 时间:2024/05/17 02:21

 1 #include<unistd.h>
      2 #include<stdio.h>
      3 #include<sys/types.h>
      4
      5 int main()
      6 {
      7         int fd[2],p;
      8         pid_t pid;
      9         char buf[7]={"hi all"},buf2[7];
     10         p=pipe(fd);
     11         if (p<0)
     12         {
     13                 perror("pipe error");
     14                 exit (1);
     15         }
     16         pid=fork();
     17         if (pid<0)
     18         {
     19                 perror("fork error");
     20                 exit (1);
     21         }
     22         if (pid>0)
     23         {
     24                 close(fd[0]);
     25                 write(fd[1],buf,7);
     26                 wait(NULL);
     27         }
     28         else
     29         {
     30                 close(fd[1]);
     31                 read(fd[0],buf2,7);
     32
     33
     34         printf("the result is %s/n",buf2);
     35
     36         }
     37         return (1);
     38 }
     39
     40 //note : 把一个字符串从一个管道传到另一个管道
     41 //       要用到ipc的原因是因为进程中的全局变量不能共享访问
     42 //      必须要经过内核缓存区中转一下
     43 //      write 对应的是stdout  read 对应的是stdin