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);

描述

pipe() 创建一个管道,这是一个单向数据通道,可用于进程间通信。pipefd 数组用于返回两个文件描述符,它们引用管道的两端。pipefd[0] 引用管道的读取端。pipefd[1] 引用管道的写入端。写入管道写入端的数据由内核缓冲,直到从管道的读取端读取。有关更多详细信息,请参阅 pipe(7)

如果 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);
    }
}

参见

fork(2), read(2), socketpair(2), write(2), popen(3), pipe(7)

引用自

capabilities(7), csh(1), event(3), eventfd(2), eventtest(6), explain(1), explain(3), explain_pipe(3), explain_pipe_or_die(3), fifo(4), fifo(7), getrlimit(2), iv_event_raw(3), ksh(1), ksh93(1), man-pages(7), mksh(1), pmdaconnect(3), sec(1), shmux(1), stat(2)