函数原型
#include <unistd.h>
int pipe(int pipefd[2]);
pipe
函数用于创建一个管道,以实现进程间通信。
fd
返回两个文件描述符,fd[0]
只读,fd[1]
只写
- 它们是
半双工
的(现在某些系统提供全双工管道) - 管道只能在具有公共祖先的两个进程之间使用
man 手册示例
单个进程中的管道没有什么用处。通常,进程会先调用 pipe
,接着调用 fork
,从而创建从父进程到子进程的IPC通道,反之亦然。
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int
main(int argc, char *argv[])
{
int pipefd[2];
pid_t cpid;
char buf;
if (argc != 2) {
fprintf(stderr, "Usage: %s <string>\n", argv[0]);
exit(EXIT_FAILURE);
}
if (pipe(pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
cpid = fork();
if (cpid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (cpid == 0) { /* 等于 0 时代表子进程 */
close(pipefd[1]); /* 关闭写 */
while (read(pipefd[0], &buf, 1) > 0)
write(STDOUT_FILENO, &buf, 1);
write(STDOUT_FILENO, "\n", 1);
close(pipefd[0]);
_exit(EXIT_SUCCESS);
} else { /* Parent writes argv[1] to pipe */
close(pipefd[0]); /* 父进程关闭读 */
write(pipefd[1], argv[1], strlen(argv[1]));
close(pipefd[1]); /* Reader will see EOF */
wait(NULL); /* Wait for child */
exit(EXIT_SUCCESS);
}
}