pipe
- 功能:有血缘关系的两个进程 (母子进程) 可以通过无名管道通信
- 原型:
int pipe(int pipefd[2]);
- 参数:
1)int pipefd[2],
a.2:提示作用(数组长度至少为2)
b.传出参数:0关联读端,1关联管道写端 - 返回值:
成功:返回0
失败:返回-1,并会设置errno - 惯用法:
a.先pipe
b.再fork
c.父进程关闭管道的一端
d.子进程关闭管道的另一端 - DO
#include <func.h>
int main(int argc, char* argv[]) {
int pipefd[2];
if (pipe(pipefd) == -1) {
error(1, errno, "pipe");
}
pid_t pid;
switch (pid = fork()) {
case -1:
error(1, errno, "fork");
case 0:
close(pipefd[1]);
char buf[1024] = "";
read(pipefd[0], buf, sizeof(buf));
puts(buf);
break;
default: {
close(pipefd[0]);
write(pipefd[1], "Who is your mommy", 18);
break;
}
}
return 0;
}