2017-02-11 58 views
2

我在一本書中讀到,爲了在兩個進程之間使用管道進行進程間通信,最好使用兩個管道,一個用於孩子寫入它和父親從它讀取和另一個做相反的溝通。爲什麼這是一個更好的方法?我們不能只使用一個管道,以便父母和孩子都可以讀取和寫入嗎?進程間通信,操作系統,管道

回答

0

您需要一種方法來同步進程之間的通信,否則一個進程將讀取/寫入一次又一次寫入/讀取的內容。例如如果你使用一個管道:

//parent 
while(1) 
{ 
    write(p1); 
    //need a logic to wait so as to read what child wrote back and also so 
    // that we may not end up reading back what we wrote. 
    read(p1); 
} 
//child 
while(1) 
{ 
    read(p1); 
    //need a logic to wait so as to read what child wrote back and also so 
    // that we may not end up reading back what we wrote. 
    write(p1); 
} 

找到一個傻瓜證明邏輯來同步或使用兩個管道。我說的是傻瓜等待,cuz簡單的技術,如sleep()signals容易受到操作系統人員在其作品中列出的那些調度問題的影響。

管道本身阻塞結構,所以要依賴它們進行同步。

//parent 
while(1) 
{ 
    write(p1); 
    //pipe blocks until till child writes something in pipe 
    read(p2); 
} 
//child 
while(1) 
{ 
    //pipe waits for parent to write. 
    read(p1); 
    //parent is waiting to read. 
    write(p2); 
}