C 管道 write/read 优先级

C pipes write/read priority

我正在尝试了解管道和 fork 在 C 中的使用。下面是一个代码示例,它调用 fork() 然后:

我的理解是,我们使用pipes,把它们当作文件,这样child进程和parent进程就可以通信了。 (这是正确的吗?)现在,由于 parent 和 child 都在使用管道,child 会读取一个空的 pipe 吗?或者 pipe 会是 "Hello world" 吗?为什么?我的猜测是它是随机的,因为 child 和 parent 同时处理 运行。这是真的 ?

根据man 7 pipe,"If a process attempts to read from an empty pipe, then read(2) will block until data is available."。

因此,如果 read 发生在 write 之前,它将等到 write 完成。

反过来,如果 read 出现在 write 之后,很明显它会 return 消息。

并且这些情况中至少有一个必须是真实的,因为,仍然根据 man 7 pipe、"POSIX.1-2001 says that write(2)s of less than PIPE_BUF bytes must be atomic",而 PIPE_BUF 通常大到足以容纳比 "Hello World".

因此 read 将 return "Hello world"。