进程间通信IPC-管道

管道是UNIX系统IPC的最古老的形式,所有的UNIX系统都提供此通讯机制。管道有以下两种局限性:

    1, 历史上,它们是半双工的(即数据只能在一个方向上流动)。现在某些系统提供了全双工管道,但是为了最佳的移植性,我们不应预先假定系统支持全双工管道。

    2,管道只能在具有公共祖先的两个进程之间使用。通常一个管道由一个进程创建,在进程调用fork之后,这个管道就能在父进程和子进程之间使用了。

管道通过调用pipe函数创建:

1 #include <unistd.h>
2 int pipe(int fd[2]); //返回值:若成功返回0,失败则返回-1

经由fd参数返回两个文件描述符:fd[0]为读而打开,fd[1]为写而打开,fd[1]的输出是fd[0]的输入。

程序创建一个从父进程到子进程的管道,并且父进程经由该管道向子进程传送数据。

 1 #include <string.h>
 2 #include <unistd.h>
 3 #include <sys/wait.h>
 4 
 5 int main(int argc, char* argv[])
 6 {
 7   int n;
 8   int fd[2];
 9   pid_t pid;
10   char line[128];
11   
12   if (pipe(fd) < 0)
13     {
14       printf("pipe error
");
15       goto exit;
16     }
17 
18   if ((pid = fork()) < 0)
19     {
20       printf("fork error
");
21       goto exit;
22     }
23   else if (pid == 0)
24     {
25       close(fd[1]);
26       n = read(fd[0], line, 128);
27       printf("Parent'Pid print something to stdout:
");
28       write(1, line, n);
29     }
30   else
31     {
32       close(fd[0]);
33       char szBuff[128] = "";
34       snprintf(szBuff, sizeof(szBuff), "i am %d, Hello Parent!
", getpid());
35       write(fd[1], szBuff, strlen(szBuff));
36     }
37 
38   if (waitpid(pid, NULL, 0) != pid)
39     {
40       printf("waitpid: i am %d 
", getpid());
41       // _exit(0);
42     }
43   printf("i am %d 
", getpid());
44 exit:
45   return 0;
46 }
输出结果:
1 $ ./a.out 
2 Parent'Pid print something to stdout:
3 i am 3339, Hello Parent!
4 waitpid: i am 3340 
5 i am 3340 
6 i am 3339

父进程和子进程通信很简单啊~!!

原文地址:https://www.cnblogs.com/borey/p/5625928.html