2015-04-06 69 views
0

父進程將數組中的整數順序寫入管道。進程如何知道何時從管道讀取

... 
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時間,它仍然不會在父級沒有寫入管道之前讀取。 這是如何工作的?

回答

4

操作系統負責這個。從管道讀取數據時,執行將會阻塞,直到有數據可用。你的程序在等待的時候不會佔用CPU時間。

4

由於沒有任何內容需要讀取表單管道,所以子進程將等待(阻塞),直到父進程寫入管道內爲止。