1. 名称 NAME
pipe, pipe2
建立管道
2. 摘要 SYNOPSIS
#include <unistd.h>
int pipe(int pipefd[2]);
#define _GNU_SOURCE /* See feature_test_macros(7) */
#include <fcntl.h> /* Obtain O_* constant definitions */
#include <unistd.h>
int pipe2(int pipefd[2], int flags);
3. 描述 DESCRIPTION
pipe() 作用就是为了创建一个管道,(PS:不懂管道的百度下,Linux中shell中管道的概念还是很重要的)。pipefd[]用于返回管道两端的文件描述符。
pipefd[0]:读取端文件描述符
pipefd[1]:写入端文件描述符
4. 返回值 RETURN VALUE
成功: 0
错误:-1
此外还可以通过errno获取
5. 错误号 ERRORS
errno 获取的错误值:
EFAULT: 非法pipefd
EINVAL : pipe2 flag 非法
EMFILE:进程处理的文件描述符太多
ENFILE:打开文件数达到系统上限
6. 版本 VERSIONS
pipe2() :
Linux version 2.6.27;
glibc version 2.9.
7. 实例
#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) { /* Child reads from pipe */
close(pipefd[1]); /* Close unused write end */
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]); /* Close unused read end */
write(pipefd[1], argv[1], strlen(argv[1]));
close(pipefd[1]); /* Reader will see EOF */
wait(NULL); /* Wait for child */
exit(EXIT_SUCCESS);
}
}
8. SEE ALSO
fork(2), read(2), socketpair(2), write(2), popen(3), pipe(7)