【问题标题】:How does a process know when to read from pipe进程如何知道何时从管道中读取
【发布时间】:2015-04-06 20:01:15
【问题描述】:

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

...
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]);
...

孩子如何知道何时从管道中读取?

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

【问题讨论】:

    标签: c pipe


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      由于没有什么要从管道中读取,子进程将等待(阻塞)直到父进程向管道中写入内容。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-07-09
        • 2015-07-03
        • 1970-01-01
        • 2016-02-06
        • 1970-01-01
        • 2010-11-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多