跳到内容

pipe / pipe2(匿名管道) · 如何使用 ​

推荐学习路径 ​

  1. 01_basic_same_process.c:先理解 pipe 的两个 fd。
  2. 02_fork_parent_to_child.c:再看 fork 后父子进程如何共享 pipe。
  3. 03_eof_after_close_write_end.c:理解为什么必须关闭不用的一端。
  4. 04_block_until_writer_sends.c:理解默认阻塞行为。
  5. 05_nonblock_empty_pipe.c:理解 O_NONBLOCK。
  6. 06_pipe2_cloexec.c:理解 O_CLOEXEC。
  7. 08_invalid_flags.c:理解错误返回和 pipefd 不变。
  8. 09_fcntl_toggle_nonblock.c:理解创建后如何改成非阻塞。
  9. 10_sigpipe_no_reader.c:理解没有读端时写入的行为。
  10. 11_pipe_buf_atomicity.c:理解 PIPE_BUF 的边界。
  11. 07_packet_mode_direct.c:最后看 packet mode,避免和普通 pipe 混淆。

demo 索引表 ​

文件功能说明预期输出
01_basic_same_process.c最小 pipe 创建、写入、读取打印两个 fd,并读回 hello pipe
02_fork_parent_to_child.cfork 后父写子读同一个 pipe子进程输出父进程写入的字符串
03_eof_after_close_write_end.c所有写端关闭后读到 EOF先读到 3 字节,再读到 EOF
04_block_until_writer_sends.c默认阻塞读行为子进程先阻塞约 2 秒,再读到 wake up
05_nonblock_empty_pipe.cpipe2(O_NONBLOCK)空读立即报 EAGAIN,再读回 data
06_pipe2_cloexec.cpipe2(O_CLOEXEC)普通 pipe 的 FD_CLOEXEC 为 off,O_CLOEXEC 为 on
07_packet_mode_direct.cpipe2(O_DIRECT) packet mode读到 abc、defg,h 被丢弃
08_invalid_flags.c非法 flags 错误处理打印 EINVAL,pipefd 保持 111/222
09_fcntl_toggle_nonblock.c用 fcntl() 后设非阻塞空读立即报 EAGAIN
10_sigpipe_no_reader.c没有读端时写入先收到 SIGPIPE,再看到 EPIPE
11_pipe_buf_atomicity.cPIPE_BUF 原子写边界打印 PIPE_BUF 常量值和说明

每个 .c 文件顶部均包含「文件示例说明」和「输出说明」注释,便于在阅读源码时 直接了解实验目标与预期输出。全部 demo 源码位于服务器 /opt/www.fukaiqiang.com/demos/pipe/,一条命令编译运行:

bash
cd /opt/www.fukaiqiang.com/demos/pipe
make        # 编译全部 11 个 demo
make run    # 依次运行全部 demo

逐个拆解 ​

1. pipe() 返回两个 fd ​

实验目的:理解 pipe(pipefd) 的最小语义,以及 pipefd[0] 和 pipefd[1] 的分工。

实验步骤:调用 pipe(pipefd) 创建 pipe;向 pipefd[1] 写入字符串; 从 pipefd[0] 读出字符串。

原理:pipefd[0] 是读端,只能读;pipefd[1] 是写端,只能写; 数据先进入内核缓冲区,再被读端取走。

注意事项:不要混淆读端和写端;应检查 pipe() 的返回值; 写入 pipe 并不等同于输出到终端,必须从读端读取后再输出。

完整代码(/opt/www.fukaiqiang.com/demos/pipe/01_basic_same_process.c):

c
/*
 * 文件示例说明:
 *   最小 pipe 示例:创建 pipe、往写端写入、从读端读出。
 *   运行:make 01_basic_same_process && ./01_basic_same_process
 *   输出说明:会打印 pipe 两端 fd,以及从读端读回的 hello pipe。
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

int
main(void)
{
    int pipefd[2];                 // pipefd[0] 放读端 fd,pipefd[1] 放写端 fd。
    const char *msg = "hello pipe"; // 准备写入 pipe 的字符串。
    char buf[64];                  // read() 读取出来的数据先放到这个缓冲区。
    ssize_t n;                     // read() 返回实际读到的字节数,可能是 -1。

    if (pipe(pipefd) == -1) {      // 创建一个单向 pipe;成功后填充 pipefd[0] 和 pipefd[1]。
        perror("pipe");           // pipe() 失败时打印 errno 对应的错误信息。
        exit(EXIT_FAILURE);        // 创建失败就不能继续演示,直接退出。
    }

    printf("read end  fd = %d\n", pipefd[0]);  // pipefd[0] 是读端,只用于 read()。
    printf("write end fd = %d\n", pipefd[1]);  // pipefd[1] 是写端,只用于 write()。

    if (write(pipefd[1], msg, strlen(msg)) == -1) { // 往写端写入 strlen(msg) 个字节。
        perror("write");                         // 写入失败时输出原因。
        exit(EXIT_FAILURE);                       // 写入失败后退出。
    }

    n = read(pipefd[0], buf, sizeof(buf) - 1); // 从读端读取数据,预留 1 字节给字符串结尾 '\0'。
    if (n == -1) {                             // read() 返回 -1 表示失败。
        perror("read");                       // 输出读取失败原因。
        exit(EXIT_FAILURE);                    // 读取失败后退出。
    }

    buf[n] = '\0';                            // read() 不会自动补 '\0',这里手动把字节序列转成 C 字符串。
    printf("read %zd bytes: %s\n", n, buf);   // 打印实际读到的字节数和内容。

    close(pipefd[0]);                         // 用完读端后关闭 fd,释放进程里的文件描述符。
    close(pipefd[1]);                         // 用完写端后关闭 fd;实际程序应检查 close() 返回值。
    return 0;
}

编译运行(make 01_basic_same_process && ./01_basic_same_process)真实输出:

text
read end  fd = 3
write end fd = 4
read 10 bytes: hello pipe

2. fork() 后父子进程共享同一个 pipe ​

实验目的:理解 fork() 之后父子进程如何共享同一个 pipe 对象。

实验步骤:pipe() 之后再 fork();父进程关闭读端,只负责写; 子进程关闭写端,只负责读。

原理:fork() 会复制 fd 表;父子进程里的 fd 编号可能相同, 但它们都指向同一个内核 pipe。

注意事项:应关闭当前进程不使用的 pipe 端; 不要误认为父子进程操作的是两个独立 pipe。

完整代码(/opt/www.fukaiqiang.com/demos/pipe/02_fork_parent_to_child.c):

c
/*
 * 文件示例说明:
 *   演示 fork() 之后父进程写、子进程读同一个 pipe。
 *   运行:make 02_fork_parent_to_child && ./02_fork_parent_to_child "hello"
 *   输出说明:子进程先打印提示,再输出父进程写入的字符串。
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>

static void
xwrite(int fd, const void *buf, size_t count)
{
    if (write(fd, buf, count) == -1) { // 对 write() 做最小错误检查,避免忽略系统调用失败。
        perror("write");              // 打印写入失败原因。
        exit(EXIT_FAILURE);            // demo 中失败就直接退出。
    }
}

int
main(int argc, char *argv[])
{
    int pipefd[2];                  // pipefd[0] 是读端,pipefd[1] 是写端。
    char buf;                       // 子进程每次只读 1 字节,用来演示字节流。
    pid_t cpid;                     // 保存 fork() 返回的子进程 pid。
    const char *msg = argc > 1 ? argv[1] : "message from parent"; // 有命令行参数就发送参数,否则发送默认字符串。

    if (pipe(pipefd) == -1) {       // fork() 之前创建 pipe,这样父子进程都会继承这两个 fd。
        perror("pipe");            // 创建失败时输出原因。
        exit(EXIT_FAILURE);         // 没有 pipe 就不能通信。
    }

    cpid = fork();                  // 创建子进程;子进程会继承 pipefd[0] 和 pipefd[1]。
    if (cpid == -1) {               // fork() 返回 -1 表示创建子进程失败。
        perror("fork");            // 输出 fork 失败原因。
        exit(EXIT_FAILURE);         // 创建失败后退出。
    }

    if (cpid == 0) {                // fork() 在子进程中返回 0,所以这里是子进程分支。
        close(pipefd[1]);           // 子进程只读,不写;关闭不用的写端,避免影响 EOF 判断。

        printf("child: reading one byte at a time: "); // 提示子进程开始读取。
        fflush(stdout);             // fork 后输出可能有缓冲,先刷新提示文本。
        while (read(pipefd[0], &buf, 1) > 0) // 从读端每次读 1 字节;写端全部关闭后会返回 0。
            xwrite(STDOUT_FILENO, &buf, 1); // 把读到的 1 字节写到标准输出。
        xwrite(STDOUT_FILENO, "\n", 1);    // 读取结束后补一个换行。

        close(pipefd[0]);           // 子进程读完后关闭读端。
        _exit(EXIT_SUCCESS);        // 子进程用 _exit() 退出,避免重复刷新父进程继承来的 stdio 缓冲。
    }

    close(pipefd[0]);               // 父进程只写,不读;关闭不用的读端。
    printf("parent: writing: %s\n", msg); // 打印父进程准备发送的内容。
    xwrite(pipefd[1], msg, strlen(msg));   // 父进程把消息写入 pipe 的写端。
    close(pipefd[1]);               // 父进程写完必须关闭写端;子进程才能最终读到 EOF。
    wait(NULL);                     // 等待子进程结束,避免产生僵尸进程。

    return 0;
}

编译运行(./02_fork_parent_to_child "hello pipe")真实输出:

text
child: reading one byte at a time: hello pipe
parent: writing: hello pipe

3. 为什么必须关闭不用的一端?EOF 依赖它 ​

实验目的:理解为什么读端只有在所有写端关闭后才会看到 EOF。

实验步骤:父进程先写入 abc;子进程先读到数据; 父进程关闭写端;子进程再次读取,得到 EOF。

原理:read() == 0 表示 EOF。EOF 的前提不是 「当前没数据」,而是「当前没数据并且所有写端都已经关闭」。

注意事项:父子进程不应保留无用写端;读进程持续阻塞时, 应优先检查是否仍有写端未关闭。

完整代码(/opt/www.fukaiqiang.com/demos/pipe/03_eof_after_close_write_end.c):

c
/*
 * 文件示例说明:
 *   演示所有写端关闭后,读端 read() 返回 0,也就是 EOF。
 *   运行:make 03_eof_after_close_write_end && ./03_eof_after_close_write_end
 *   输出说明:子进程先读到 3 字节,再在写端关闭后读到 EOF。
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>

static void
xwrite(int fd, const void *buf, size_t count)
{
    if (write(fd, buf, count) == -1) { // 包装 write(),确保写失败时能看见错误。
        perror("write");              // 输出 errno 对应的错误消息。
        exit(EXIT_FAILURE);            // demo 中写失败就退出。
    }
}

int
main(void)
{
    int pipefd[2];                 // pipefd[0] 读端,pipefd[1] 写端。
    char buf[32];                  // 子进程读取 pipe 数据的缓冲区。
    ssize_t n;                     // 保存 read() 的返回值:>0 字节数,0 EOF,-1 错误。
    pid_t cpid;                    // 保存 fork() 的返回值。

    if (pipe(pipefd) == -1) {      // 创建 pipe,让父子进程共享同一个通信通道。
        perror("pipe");           // 创建失败时打印原因。
        exit(EXIT_FAILURE);        // 创建失败后退出。
    }

    cpid = fork();                 // fork 后父子进程各自拥有一份 fd 表,但指向同一个 pipe。
    if (cpid == -1) {              // fork 失败检查。
        perror("fork");           // 输出失败原因。
        exit(EXIT_FAILURE);        // 退出。
    }

    if (cpid == 0) {               // 子进程负责读取。
        close(pipefd[1]);          // 子进程不写;关闭自己的写端,否则 EOF 可能迟迟不到。

        while ((n = read(pipefd[0], buf, sizeof(buf))) > 0) // 有数据就读取;返回 0 才是 EOF。
            printf("child: read %zd bytes\n", n);          // 打印本次读到的字节数。

        if (n == 0)                // read() 返回 0 表示没有数据且所有写端都关闭。
            printf("child: read returned 0, EOF because every write end is closed\n");
        else                       // n == -1 表示读取失败。
            perror("read");       // 输出读取失败原因。

        fflush(stdout);            // _exit() 不会刷新 stdio 缓冲,所以手动刷新。
        close(pipefd[0]);          // 子进程读完关闭读端。
        _exit(n == -1 ? EXIT_FAILURE : EXIT_SUCCESS); // 根据 read() 是否出错决定子进程退出码。
    }

    close(pipefd[0]);              // 父进程不读;关闭读端。
    xwrite(pipefd[1], "abc", strlen("abc")); // 父进程写入 3 个字节。
    sleep(1);                      // 暂停 1 秒,方便观察子进程先读到数据但还没 EOF。
    printf("parent: closing write end now\n"); // 提示马上关闭写端。
    close(pipefd[1]);              // 所有写端关闭后,子进程下一次 read() 会返回 0。
    wait(NULL);                    // 等待子进程退出。

    return 0;
}

编译运行真实输出:

text
child: read 3 bytes
child: read returned 0, EOF because every write end is closed
parent: closing write end now

4. 默认是阻塞 I/O ​

实验目的:理解空 pipe 上的默认 read() 行为。

实验步骤:子进程立即调用 read();父进程故意睡 2 秒; 父进程再写入数据。

原理:默认 pipe 是阻塞的。pipe 为空且写端还开着时,read() 会等数据; pipe 为空且所有写端关闭时,read() 才返回 0。

注意事项:不要将正常的阻塞等待误判为死锁; 写端未关闭会导致读端无法获得 EOF。

完整代码(/opt/www.fukaiqiang.com/demos/pipe/04_block_until_writer_sends.c):

c
/*
 * 文件示例说明:
 *   演示默认阻塞行为:pipe 为空且写端还开着时,read() 会等待。
 *   运行:make 04_block_until_writer_sends && ./04_block_until_writer_sends
 *   输出说明:子进程会先卡住约 2 秒,再收到 wake up。
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>

static long
now_sec(void)
{
    return (long) time(NULL);       // 返回当前秒级时间戳,用来观察阻塞等待了多久。
}

static void
xwrite(int fd, const void *buf, size_t count)
{
    if (write(fd, buf, count) == -1) { // 检查 write() 是否失败。
        perror("write");              // 输出失败原因。
        exit(EXIT_FAILURE);            // demo 中失败就退出。
    }
}

int
main(void)
{
    int pipefd[2];                 // pipefd[0] 读端,pipefd[1] 写端。
    char buf[64];                  // 子进程读取数据的缓冲区。
    ssize_t n;                     // 保存 read() 返回值。
    pid_t cpid;                    // 保存 fork() 返回值。

    if (pipe(pipefd) == -1) {      // 创建默认阻塞模式的 pipe。
        perror("pipe");           // 输出 pipe 创建失败原因。
        exit(EXIT_FAILURE);        // 创建失败后退出。
    }

    cpid = fork();                 // 创建子进程,共享 pipe 两端。
    if (cpid == -1) {              // fork 失败检查。
        perror("fork");           // 输出失败原因。
        exit(EXIT_FAILURE);        // 退出。
    }

    if (cpid == 0) {               // 子进程演示阻塞 read()。
        close(pipefd[1]);          // 子进程不写;关闭写端。
        printf("%ld child: read() starts and will block until data arrives\n", now_sec()); // read 前打印时间。
        fflush(stdout);            // 立即输出提示,避免缓冲影响观察。
        n = read(pipefd[0], buf, sizeof(buf) - 1); // pipe 为空但写端仍开着时,默认 read() 会阻塞。
        if (n == -1) {             // read() 失败检查。
            perror("read");       // 输出失败原因。
            _exit(EXIT_FAILURE);   // 子进程失败退出。
        }
        buf[n] = '\0';            // 把读到的字节转换成 C 字符串。
        printf("%ld child: read() returned %zd bytes: %s\n", now_sec(), n, buf); // 打印 read 返回时间和内容。
        fflush(stdout);            // _exit() 前刷新输出。
        close(pipefd[0]);          // 关闭读端。
        _exit(EXIT_SUCCESS);       // 子进程正常退出。
    }

    close(pipefd[0]);              // 父进程不读;关闭读端。
    sleep(2);                      // 故意等待 2 秒,让子进程卡在 read() 上。
    printf("%ld parent: writing after 2 seconds\n", now_sec()); // 打印父进程写入时间。
    xwrite(pipefd[1], "wake up", strlen("wake up")); // 写入数据后,阻塞的子进程 read() 会返回。
    close(pipefd[1]);              // 写完关闭写端。
    wait(NULL);                    // 等待子进程结束。

    return 0;
}

编译运行真实输出(每行前缀是秒级时间戳,可以看到读端整整阻塞了 2 秒):

c
1785916754 child: read() starts and will block until data arrives
1785916756 child: read() returned 7 bytes: wake up
1785916756 parent: writing after 2 seconds

5. pipe2(O_NONBLOCK):创建时直接非阻塞 ​

实验目的:理解非阻塞 pipe 的空读行为。

实验步骤:用 pipe2(..., O_NONBLOCK) 创建 pipe;对空 pipe 执行 read(); 再写入 data,然后再次读取。

原理:O_NONBLOCK 让空读不再等待;常见错误码是 EAGAIN 或 EWOULDBLOCK(二者在 Linux 上数值相同)。

注意事项:非阻塞 I/O 应处理 EAGAIN;非阻塞空读通常返回 -1 并设置 errno,不会返回空字符串。

完整代码(/opt/www.fukaiqiang.com/demos/pipe/05_nonblock_empty_pipe.c):

c
/*
 * 文件示例说明:
 *   演示 pipe2(O_NONBLOCK) 创建非阻塞 pipe,空读会立即返回。
 *   运行:make 05_nonblock_empty_pipe && ./05_nonblock_empty_pipe
 *   输出说明:空读会立即报 EAGAIN,写入 data 后立刻读回 4 字节。
 */
#define _GNU_SOURCE              // 启用 GNU 扩展声明,使 pipe2() 原型可见。
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

static void
xwrite(int fd, const void *buf, size_t count)
{
    if (write(fd, buf, count) == -1) { // 写入失败时返回 -1。
        perror("write");              // 输出失败原因。
        exit(EXIT_FAILURE);            // demo 中失败就退出。
    }
}

int
main(void)
{
    int pipefd[2];                 // pipefd[0] 读端,pipefd[1] 写端。
    char buf[16];                  // read() 的目标缓冲区。
    ssize_t n;                     // 保存 read() 返回值。

    if (pipe2(pipefd, O_NONBLOCK) == -1) { // 创建 pipe,并把读写端对应的 open file description 设为非阻塞。
        perror("pipe2");          // 输出 pipe2 失败原因。
        exit(EXIT_FAILURE);        // 创建失败后退出。
    }

    n = read(pipefd[0], buf, sizeof(buf)); // pipe 为空,且 fd 是非阻塞,所以 read() 不会等待。
    if (n == -1)                  // 非阻塞空读通常返回 -1。
        printf("read empty nonblocking pipe: -1, errno=%d (%s)\n", errno, strerror(errno)); // 常见 errno 是 EAGAIN/EWOULDBLOCK。
    else                          // 如果返回其他值,也打印出来便于观察。
        printf("read returned %zd\n", n);

    xwrite(pipefd[1], "data", 4); // 往 pipe 写入 4 字节数据。
    n = read(pipefd[0], buf, sizeof(buf)); // 现在 pipe 有数据,非阻塞 read() 可以立即读到。
    if (n == -1) {                // 读已有数据仍失败就说明有异常。
        perror("read after write"); // 输出失败原因。
        exit(EXIT_FAILURE);       // 退出。
    }

    printf("read after write: %zd bytes: %.*s\n", n, (int) n, buf); // 用 %.*s 打印非 '\0' 结尾的字节序列。

    close(pipefd[0]);             // 关闭读端。
    close(pipefd[1]);             // 关闭写端。
    return 0;
}

编译运行真实输出:

c
read empty nonblocking pipe: -1, errno=11 (Resource temporarily unavailable)
read after write: 4 bytes: data

6. pipe2(O_CLOEXEC):避免 exec 泄漏 fd ​

实验目的:理解 FD_CLOEXEC 的作用。

实验步骤:创建一个普通 pipe;再创建一个 O_CLOEXEC pipe; 用 fcntl(F_GETFD) 检查 FD_CLOEXEC。

原理:exec() 后,带 FD_CLOEXEC 的 fd 会自动关闭, 这能防止子程序意外继承 pipe fd。

注意事项:在多线程程序中,先 pipe() 再 fcntl() 可能产生竞态窗口; 未设置 FD_CLOEXEC 可能导致 fd 泄漏到 exec 后的程序。

完整代码(/opt/www.fukaiqiang.com/demos/pipe/06_pipe2_cloexec.c):

c
/*
 * 文件示例说明:
 *   演示 pipe2(O_CLOEXEC) 给新建 fd 直接设置 FD_CLOEXEC。
 *   运行:make 06_pipe2_cloexec && ./06_pipe2_cloexec
 *   输出说明:普通 pipe 的 FD_CLOEXEC 是 off,O_CLOEXEC pipe 是 on。
 */
#define _GNU_SOURCE              // 启用 pipe2() 所需的 GNU 扩展声明。
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

static void
print_cloexec(const char *name, int fd)
{
    int flags = fcntl(fd, F_GETFD); // 读取 fd flags;FD_CLOEXEC 属于 fd flag,不是 file status flag。
    if (flags == -1) {              // fcntl() 失败检查。
        perror("fcntl");           // 输出失败原因。
        exit(EXIT_FAILURE);         // demo 中失败就退出。
    }

    printf("%s fd=%d FD_CLOEXEC=%s\n", name, fd,
           (flags & FD_CLOEXEC) ? "on" : "off"); // 判断 FD_CLOEXEC 位是否已设置。
}

int
main(void)
{
    int plain[2];                  // 普通 pipe() 创建出来的两个 fd。
    int cloexec[2];                // pipe2(O_CLOEXEC) 创建出来的两个 fd。

    if (pipe(plain) == -1) {       // 普通 pipe() 不会自动设置 FD_CLOEXEC。
        perror("pipe");           // 输出失败原因。
        exit(EXIT_FAILURE);        // 创建失败后退出。
    }

    if (pipe2(cloexec, O_CLOEXEC) == -1) { // 创建 pipe 时原子地给两个 fd 设置 close-on-exec。
        perror("pipe2");          // 输出失败原因。
        exit(EXIT_FAILURE);        // 创建失败后退出。
    }

    print_cloexec("plain read end", plain[0]);       // 检查普通 pipe 的读端。
    print_cloexec("plain write end", plain[1]);      // 检查普通 pipe 的写端。
    print_cloexec("cloexec read end", cloexec[0]);   // 检查 O_CLOEXEC pipe 的读端。
    print_cloexec("cloexec write end", cloexec[1]);  // 检查 O_CLOEXEC pipe 的写端。

    close(plain[0]);                // 关闭普通 pipe 读端。
    close(plain[1]);                // 关闭普通 pipe 写端。
    close(cloexec[0]);              // 关闭 cloexec pipe 读端。
    close(cloexec[1]);              // 关闭 cloexec pipe 写端。
    return 0;
}

编译运行真实输出:

text
plain read end fd=3 FD_CLOEXEC=off
plain write end fd=4 FD_CLOEXEC=off
cloexec read end fd=5 FD_CLOEXEC=on
cloexec write end fd=6 FD_CLOEXEC=on

7. pipe2(O_DIRECT) 的 packet mode ​

实验目的:理解 packet mode 和普通字节流 pipe 的区别。

实验步骤:用 pipe2(..., O_DIRECT) 创建 pipe;写入两个 packet: abc 和 defgh;用较小 buffer 读取。

原理:packet mode 下,每次 write() 都是独立 packet;每次 read() 最多取一个 packet;读 buffer 小于 packet 时,剩余部分会被丢弃。

注意事项:不要将 packet mode 等同于普通字节流模式;packet mode 中 读缓冲区不足时,packet 剩余部分会被丢弃,后续 read() 无法补读。

完整代码(/opt/www.fukaiqiang.com/demos/pipe/07_packet_mode_direct.c):

c
/*
 * 文件示例说明:
 *   演示 pipe2(O_DIRECT) 的 packet mode:每次 write() 作为一个 packet。
 *   运行:make 07_packet_mode_direct && ./07_packet_mode_direct
 *   输出说明:第一次读到 abc,第二次读到 defg,h 被 packet mode 丢弃。
 */
#define _GNU_SOURCE              // 启用 pipe2() 和 O_DIRECT 等 GNU/Linux 扩展声明。
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

static void
xwrite(int fd, const void *buf, size_t count)
{
    if (write(fd, buf, count) == -1) { // 检查 write() 是否失败。
        perror("write");              // 输出失败原因。
        exit(EXIT_FAILURE);            // demo 中失败就退出。
    }
}

int
main(void)
{
    int pipefd[2];                 // pipefd[0] 读端,pipefd[1] 写端。
    char buf[8];                   // 故意准备较小的读取缓冲区,演示 packet 尾部丢弃。
    ssize_t n;                     // 保存 read() 返回值。

    if (pipe2(pipefd, O_DIRECT) == -1) { // 对 pipe 使用 O_DIRECT 表示 packet mode,不是普通文件 direct I/O。
        if (errno == EINVAL) {          // 老内核可能不支持 pipe 的 O_DIRECT packet mode。
            fprintf(stderr, "O_DIRECT packet mode is not supported by this kernel\n"); // 友好提示。
            return EXIT_SUCCESS;        // 不把内核不支持当作 demo 失败。
        }
        perror("pipe2");               // 其他错误正常打印。
        exit(EXIT_FAILURE);             // 退出。
    }

    xwrite(pipefd[1], "abc", 3);   // 第一次 write() 形成第一个 packet:abc。
    xwrite(pipefd[1], "defgh", 5); // 第二次 write() 形成第二个 packet:defgh。

    n = read(pipefd[0], buf, 4);    // 每次 read() 最多读取一个 packet;第一个 packet 只有 3 字节。
    printf("first read buffer=4 -> %zd bytes: %.*s\n", n, (int) n, buf); // 预期读到 abc。

    n = read(pipefd[0], buf, 4);    // 第二个 packet 有 5 字节,但这里只给 4 字节 buffer。
    printf("second read buffer=4 -> %zd bytes: %.*s\n", n, (int) n, buf); // 预期读到 defg。
    printf("packet mode discards the unread tail of the second packet, so 'h' is gone\n"); // 剩余的 h 会被丢弃。

    close(pipefd[0]);              // 关闭读端。
    close(pipefd[1]);              // 关闭写端。
    return 0;
}

编译运行真实输出:

c
first read buffer=4 -> 3 bytes: abc
second read buffer=4 -> 4 bytes: defg
packet mode discards the unread tail of the second packet, so 'h' is gone

8. 错误时返回 -1,pipefd 不变 ​

实验目的:理解 pipe2() 出错时的返回值和输出参数行为。

实验步骤:用非法 flags 调用 pipe2();检查 errno; 检查 pipefd 是否被改写。

原理:pipe2() 失败时返回 -1;Linux 和 POSIX 要求失败时不修改 pipefd。

注意事项:系统调用失败后,不应继续把 pipefd 当成有效 fd 使用; 应检查 errno 以确认失败原因。

完整代码(/opt/www.fukaiqiang.com/demos/pipe/08_invalid_flags.c):

c
/*
 * 文件示例说明:
 *   演示 pipe2() 传入非法 flags 时返回 EINVAL,且 pipefd 保持不变。
 *   运行:make 08_invalid_flags && ./08_invalid_flags
 *   输出说明:会打印 EINVAL,并显示 pipefd 仍保持为 111/222。
 */
#define _GNU_SOURCE              // 启用 pipe2() 声明。
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

int
main(void)
{
    int pipefd[2] = {111, 222};    // 先放入哨兵值,用来观察失败后 pipefd 是否被修改。

    if (pipe2(pipefd, 0xdeadbeef) == -1) { // 传入非法 flags,预期 pipe2() 失败。
        printf("pipe2 failed: errno=%d (%s)\n", errno, strerror(errno)); // 非法 flags 对应 EINVAL。
        printf("pipefd remains unchanged on failure: [%d, %d]\n", pipefd[0], pipefd[1]); // Linux/POSIX 要求失败时不修改 pipefd。
        return EXIT_SUCCESS;       // 失败是本 demo 预期结果,所以返回成功。
    }

    fprintf(stderr, "unexpected success\n"); // 如果非法 flags 居然成功,说明不符合预期。
    close(pipefd[0]);              // 意外成功时关闭读端,避免 fd 泄漏。
    close(pipefd[1]);              // 意外成功时关闭写端。
    return EXIT_FAILURE;           // 意外成功视为 demo 失败。
}

编译运行真实输出:

c
pipe2 failed: errno=22 (Invalid argument)
pipefd remains unchanged on failure: [111, 222]

9. pipe() 后也可以用 fcntl() 修改状态 ​

实验目的:理解创建后如何把读端改成非阻塞。

实验步骤:先调用 pipe();再用 fcntl(F_GETFL)/fcntl(F_SETFL) 添加 O_NONBLOCK;对空 pipe 读一次。

原理:O_NONBLOCK 属于 file status flag,可以在创建后通过 fcntl() 修改。

注意事项:应确认修改的是实际需要非阻塞行为的 fd;O_NONBLOCK 既可以在 pipe2() 中设置,也可以通过 fcntl() 后续设置。

完整代码(/opt/www.fukaiqiang.com/demos/pipe/09_fcntl_toggle_nonblock.c):

c
/*
 * 文件示例说明:
 *   演示先用 pipe() 创建,再用 fcntl() 把读端改成非阻塞。
 *   运行:make 09_fcntl_toggle_nonblock && ./09_fcntl_toggle_nonblock
 *   输出说明:空读会立即返回 EAGAIN,证明 fcntl 已把读端改成非阻塞。
 */
#define _GNU_SOURCE              // 启用 GNU/Linux 相关声明。
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

static void
set_nonblock(int fd)
{
    int flags = fcntl(fd, F_GETFL); // 读取 file status flags,例如 O_NONBLOCK。
    if (flags == -1) {              // F_GETFL 失败检查。
        perror("fcntl F_GETFL");   // 输出失败原因。
        exit(EXIT_FAILURE);         // 失败后退出。
    }

    if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) { // 在原有 flags 基础上追加 O_NONBLOCK。
        perror("fcntl F_SETFL");   // 输出设置失败原因。
        exit(EXIT_FAILURE);         // 失败后退出。
    }
}

int
main(void)
{
    int pipefd[2];                 // pipefd[0] 读端,pipefd[1] 写端。
    char buf[16];                  // read() 使用的缓冲区。
    ssize_t n;                     // 保存 read() 返回值。

    if (pipe(pipefd) == -1) {      // 先创建普通阻塞 pipe。
        perror("pipe");           // 输出创建失败原因。
        exit(EXIT_FAILURE);        // 创建失败后退出。
    }

    set_nonblock(pipefd[0]);       // 只把读端改成非阻塞;写端仍保持原状态。
    n = read(pipefd[0], buf, sizeof(buf)); // 空 pipe 上非阻塞 read() 会立即返回,不会卡住。
    if (n == -1)                   // 预期返回 -1。
        printf("after fcntl O_NONBLOCK, empty read -> errno=%d (%s)\n",
               errno, strerror(errno)); // 常见 errno 是 EAGAIN/EWOULDBLOCK。

    close(pipefd[0]);              // 关闭读端。
    close(pipefd[1]);              // 关闭写端。
    return 0;
}

编译运行真实输出:

c
after fcntl O_NONBLOCK, empty read -> errno=11 (Resource temporarily unavailable)

10. 没有读端时写入:SIGPIPE 和 EPIPE ​

实验目的:理解没有 reader 时写入 pipe 的行为。

实验步骤:安装 SIGPIPE 处理函数;关闭唯一读端;向写端写 1 字节。

原理:没有读端时,再写 pipe 会触发 SIGPIPE,其默认动作是终止进程; 如果捕获了信号,write() 会返回 -1,errno = EPIPE。

注意事项:应注意 SIGPIPE 的默认动作通常是终止进程; EPIPE 通常表示 pipe 已经没有读者。

完整代码(/opt/www.fukaiqiang.com/demos/pipe/10_sigpipe_no_reader.c):

c
/*
 * 文件示例说明:
 *   演示没有读端时向 pipe 写入会触发 SIGPIPE,write() 返回 EPIPE。
 *   运行:make 10_sigpipe_no_reader && ./10_sigpipe_no_reader
 *   输出说明:先打印 SIGPIPE,再打印 write() 的 EPIPE。
 */
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

static void
sigpipe_handler(int sig)
{
    printf("caught signal %d (SIGPIPE): there is no reader\n", sig); // 捕获 SIGPIPE,避免默认动作直接终止进程。
}

int
main(void)
{
    int pipefd[2];                 // pipefd[0] 读端,pipefd[1] 写端。
    ssize_t n;                     // 保存 write() 返回值。

    if (signal(SIGPIPE, sigpipe_handler) == SIG_ERR) { // 安装 SIGPIPE 处理函数。
        perror("signal");         // 输出安装失败原因。
        exit(EXIT_FAILURE);        // 安装失败后退出。
    }

    if (pipe(pipefd) == -1) {      // 创建一个普通 pipe。
        perror("pipe");           // 输出创建失败原因。
        exit(EXIT_FAILURE);        // 创建失败后退出。
    }

    close(pipefd[0]);              // 关闭唯一的读端,制造“没有 reader”的场景。
    n = write(pipefd[1], "x", 1);  // 向没有读端的 pipe 写入,会触发 SIGPIPE。
    if (n == -1)                   // 捕获 SIGPIPE 后,write() 返回 -1。
        printf("write returned -1, errno=%d (%s)\n", errno, strerror(errno)); // errno 通常是 EPIPE。
    else                           // 如果 write() 成功,也打印实际写入字节数。
        printf("write returned %zd\n", n);

    close(pipefd[1]);              // 关闭写端。
    return 0;
}

编译运行真实输出:

c
caught signal 13 (SIGPIPE): there is no reader
write returned -1, errno=32 (Broken pipe)

11. PIPE_BUF 和原子写 ​

实验目的:理解 pipe 写入原子性的边界。

实验步骤:打印 PIPE_BUF 的值;观察讲义说明。

原理:多个写者写同一个 pipe 时,不大于 PIPE_BUF 的单次写不会交叉混杂; 超过 PIPE_BUF 时,内核可以拆分。

注意事项:不要误认为 pipe 中任意大小的写入都具备原子性; 大块数据写入可能被拆分,不应直接视为不可分割消息。

完整代码(/opt/www.fukaiqiang.com/demos/pipe/11_pipe_buf_atomicity.c):

c
/*
 * 文件示例说明:
 *   演示 PIPE_BUF 的概念:不大于它的 pipe 写入具有原子性。
 *   运行:make 11_pipe_buf_atomicity && ./11_pipe_buf_atomicity
 *   输出说明:打印系统的 PIPE_BUF 常量值,并说明原子写边界。
 */
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int
main(void)
{
    int pipefd[2];                 // 创建 pipe 只是为了让示例语境完整;本 demo 主要打印 PIPE_BUF。

    if (pipe(pipefd) == -1) {      // 创建普通 pipe。
        perror("pipe");           // 输出创建失败原因。
        exit(EXIT_FAILURE);        // 创建失败后退出。
    }

    printf("PIPE_BUF from <limits.h> = %ld\n", (long) PIPE_BUF); // PIPE_BUF 是 pipe 原子写大小边界。
    printf("Writes no larger than PIPE_BUF bytes are atomic for a pipe.\n"); // 不超过 PIPE_BUF 的单次写不会与其他写者交叉。
    printf("O_DIRECT packet mode may split writes larger than PIPE_BUF into packets.\n"); // packet mode 下大写入可能被拆包。

    close(pipefd[0]);              // 关闭读端。
    close(pipefd[1]);              // 关闭写端。
    return 0;
}

编译运行真实输出:

text
PIPE_BUF from <limits.h> = 4096
Writes no larger than PIPE_BUF bytes are atomic for a pipe.
O_DIRECT packet mode may split writes larger than PIPE_BUF into packets.

常见坑 ​

坑 1:忘记关闭不用的一端 ​

最典型后果:读端迟迟等不到 EOF。父进程只写、子进程只读时:

c
// child
close(pipefd[1]);

// parent
close(pipefd[0]);

并且父进程写完后还要 close(pipefd[1]);。

坑 2:以为 pipe 是双向的 ​

pipe() 是单向的。父子双向通信要两个 pipe(parent→child 一个, child→parent 一个),或者使用 socketpair(2)。

坑 3:没有处理短读/短写 ​

read() 和 write() 返回的是实际处理的字节数,不一定等于请求的字节数。 教学 demo 为了聚焦 pipe 行为,代码较短;生产代码通常需要循环读写直到完成 或遇到错误/EOF。

坑 4:忽略错误返回值 ​

系统调用常见模式:

c
if (pipe(pipefd) == -1) {
    perror("pipe");
    exit(EXIT_FAILURE);
}

read()、write()、close()、fork()、fcntl() 也应按需检查。

与 man page(pipe(2))的对应关系 ​

  • NAME/SYNOPSIS:对应所有 demo 中的 pipe()/pipe2() 调用。
  • DESCRIPTION 中的 pipefd[0]、pipefd[1]:对应 01、02。
  • O_CLOEXEC:对应 06_pipe2_cloexec.c。
  • O_DIRECT packet mode:对应 07_packet_mode_direct.c。
  • O_NONBLOCK:对应 05_nonblock_empty_pipe.c 和 09_fcntl_toggle_nonblock.c。
  • RETURN VALUE 和失败时 pipefd 不变:对应 08_invalid_flags.c。
  • EXAMPLES 的父写子读:对应 02_fork_parent_to_child.c, 并在 03、04 拆出 EOF/阻塞细节。

© fukaiqiang.com · 个人技术学习笔记 · 冀ICP备2026026950号 · 京公网安备11010802049509号