pipe(2) - Linux 手册页
名称
pipe, pipe2 - 创建管道概要
#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);
描述
如果 flags 为 0,则 pipe2() 与 pipe() 相同。以下值可以按位或运算到 flags 中以获得不同的行为
- O_NONBLOCK
- 在两个新的打开文件描述符上设置 O_NONBLOCK 文件状态标志。使用此标志可以节省额外的调用 fcntl(2) 以达到相同结果。
- O_CLOEXEC
- 在两个新的文件描述符上设置关闭时执行 (FD_CLOEXEC) 标志。有关为什么这可能很有用的原因,请参阅 open(2) 中对相同标志的描述。
返回值
成功时返回零。出错时返回 -1,并相应地设置 errno。错误
- EFAULT
- pipefd 无效。
- EINVAL
- (pipe2()) flags 中的无效值。
- EMFILE
- 进程使用的文件描述符过多。
- ENFILE
- 已达到系统打开文件总数的限制。
版本
pipe2() 在 Linux 版本 2.6.27 中添加;glibc 支持从版本 2.9 开始可用。符合
pipe(): POSIX.1-2001。pipe2() 是 Linux 特有的。
示例
以下程序创建一个管道,然后 fork(2) 创建一个子进程;子进程继承一组重复的文件描述符,这些文件描述符引用同一个管道。在 fork(2) 之后,每个进程关闭它不需要用于管道的描述符(请参阅 pipe(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); } }