进程如何知道何时从管道读取

How does a process know when to read from pipe

parent 进程将数组中的整数按顺序写入管道。

...
close(thePipe[0]);
int array[]={1, 2, 5, 5, 5};
int j;

for(j=0; j<sizeof(array)/sizeof(int); j++){
  write(thePipe[1], &(array[j]), sizeof(int));
}
close(thePipe[1];
...

它的 child 进程读取这些整数并将它们相加。

...
close(thePipe[1]);
int sum = 0;
int buffer;
while( 0 != read(thePipe[0], &buffer, sizeof(buffer)) ){
  sum = sum + buffer;
}
close(thePipe[0]);
...

child 如何知道何时从管道读取数据?

即使 child 获得更多 CPU 时间,它仍然不会在 parent 未写入管道之前读取。 这是如何运作的?

OS 会处理这个问题。当您从管道读取时,执行将阻塞直到有数据可用。您的程序在等待时不会使用 CPU 时间。

由于没有任何东西可以从管道中读取,子进程将等待(阻塞)直到父进程向管道中写入内容。