C 流程如何知道何时从管道中读取

C 流程如何知道何时从管道中读取,c,pipe,C,Pipe,父进程将整数从数组顺序写入管道 ... 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]; ... 孩子怎么知道什么时候该从管子里读 即使子进程获得了更多的CPU时间,在父进程没有写入管道之前,它仍然不

父进程将整数从数组顺序写入管道

...
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];
...
孩子怎么知道什么时候该从管子里读

即使子进程获得了更多的CPU时间,在父进程没有写入管道之前,它仍然不会读取。
这是怎么回事

操作系统会处理这个问题。当您从管道中读取数据时,执行将被阻止,直到有可用的数据为止。您的程序在以这种方式等待时不会占用CPU时间。

因为没有任何内容可从管道读取,所以子进程将等待阻塞,直到父进程将某些内容写入管道

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