parent 进程中的 read() 是否等待管道中的 child write()?

Does a read() in parent process wait for a child write() in a pipe?

我想在 C 中的 child-writer 和 parent-reader 之间创建一个管道。 我认为我的 parent 进程必须等待它的 child 写入缓冲区才能读取它,但后来我想检查它所以我写了以下代码:

pipe(fd);
// ... checks for pipe
pid_t pid = fork();
// ... checks for fork
if (pid == 0) {
    close(fd[0]);
    // Long sleep hoping parent will terminate before the write()
    sleep(10);
    write(fd[1], "hello", strlen("hello") + 1);
    close(fd[1]);
} else {
    close(fd[1]);
    read(fd[0], buf, sizeof(buf));
    printf("received: %s\n", buf);
    close(fd[0]);
}
return 0;

输出出乎意料(或者不是?)received: hello。 如果我用 for (volatile int i = 0; i < some_big_int; ++i); 循环替换对 sleep() 的调用,则输出相同。 我不认为对 read() 的调用会阻塞我的 parent 进程,直到 child 在管道的另一端写入,但我无法解释这种行为。有什么提示吗?

read 将阻塞,直到至少有一个字节要读取,或者遇到错误,或者到达流的末尾。当至少有一个字节要读取时,它将读取尽可能多的字节(直到您指定的最大数量)然后 return.

在这种情况下,父进程对 read 的调用将阻塞,直到子进程 write 向管道发送内容。


来自 man 7 pipe 部分 I/O 关于管道和 FIFO :

If a process attempts to read from an empty pipe, then read(2) will block until data is available. If a process attempts to write to a full pipe (see below), then write(2) blocks until sufficient data has been read from the pipe to allow the write to complete. Nonblocking I/O is possible by using the fcntl(2) F_SETFL operation to enable the O_NONBLOCK open file status flag.