#include <unistd.h>
#include <stdio.h>
int main()
{
char buff[100];
int pfd[2];
buff[0] = '\0';
pipe(pfd);
if (fork())
write(pfd[1],"hello world", 12);
fork();
read(pfd[0], buff, 100);
printf("%s\n", buff);
printf("goodbye\n");
}
我理解只有一个进程会写入管道,但我不明白的是,一个进程可以从管道中读取并只读取“hello world”的一部分而其他进程读取“你好世界”的其他部分?
换句话说,当一个进程尝试读取管道而另一个进程正在读取它时会发生什么?
答案 0 :(得分:3)
Demons will fly from your nose!
实际上,如果他们从同一个管道读取,那么他们holding file descriptors指向内核中的相同struct file
。这意味着内核将确定谁获取数据。只有一个进程将读取任何给定的字节。
对管道的大多数读写都有PIPE_BUF
的一些保证,你可能想看一下。