Linux-进程间通信(一): 管道

1. 管道局限性:

(1) 半双工;(若模拟全双工,可以使用两个管道,即,proc1-->proc2一条管道,proc2-->proc1一条管道)

(2) 只能在具有公共祖先的进程之间使用;

2. 管道创建函数:

#include <unistd.h>

int pipe (int filedes[2]);

ret = 0-成功 -1-失败

经由filedes返回两个文件描述符:filedes[0]为读端,filedes[1]为写端;

3. 惯用方式:

由于单个进程中的管道并没有任何用户,所以,通常调用pipe的进程会接着调用fork,这样就创建了从父进程到子进程(或相反)的IPC通道;

比如为了创建从子进程到父进程的管道,子进程关闭读端fd[0],父进程关闭写端fd[1];

4. 一端关闭影响:

(1) 读一个写端已经被关闭的管道,数据被读取完毕后,会读到一个文件结束符,read返回0;

(2) 写一个读端已经被关闭的管道,会产生SIGPIPE信号;

5. 管道测试:从父进程向子进程传递数据

 1 #include <unistd.h>
 2 #include <stdio.h>
 3 #include <stdlib.h>
 4 #include <string.h>
 5 
 6 #define MAX_LINE_SIZE 64
 7 
 8 int main(int argc, char *argv[])
 9 {
10     int n;
11     int fd[2];
12     pid_t pid;
13     char line[MAX_LINE_SIZE];
14 
15     if (pipe(fd) < 0){
16         perror("pipe error");
17         return -1;
18     }
19 
20     if ((pid = fork()) < 0){
21         perror("fork error");
22         return -1;
23     } else if (pid > 0){
24         close(fd[0]);
25         char * test_string = "hello world~
";
26         write(fd[1], test_string, strlen(test_string));
27         wait(NULL);
28         close(fd[1]);
29     } else {
30         close(fd[1]);
31         n = read(fd[0], line, MAX_LINE_SIZE);
32         write(STDOUT_FILENO, line, n);
33         close(fd[0]);
34     }
35 
36     return 0;
37 }
原文地址:https://www.cnblogs.com/wanpengcoder/p/5294137.html