父进程将数组中的整数按顺序写入管道。
...
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];
...
它的子进程读取这些整数并将它们相加。
...
close(thePipe[1]);
int sum = 0;
int buffer;
while( 0 != read(thePipe[0], &buffer, sizeof(buffer)) ){
sum = sum + buffer;
}
close(thePipe[0]);
...
child 如何知道何时从管道中读取?
即使子进程获得更多的 CPU 时间,在父进程没有写入管道之前它仍然不会读取。 这是如何运作的?
最佳答案
操作系统会处理这个。当您从管道读取时,执行将阻塞直到有数据可用。您的程序在等待时不会使用 CPU 时间。
关于c - 进程如何知道何时从管道读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29478705/