簡體   English   中英

如何使用管道同步父進程和子進程?

[英]How do I synchronize father and child processes using pipes?

我相信有一種方法可以使用管道同步兩個進程,但我不確定如何實現它。 在我的代碼中,子進程和父進程同時執行其代碼,我希望一個進程等待另一個進程。 例如,使用管道阻止一個進程,直到完成另一個進程。

我的代碼:

int main()
{

int one[2];
int two[2];
int x=0;
char messageRead[256], messageRead2[256], messageWrite[256], messageWrite2[256];

pipe(one);
pipe(two);

pid_t pid = fork();

if(pid == 0)  //child process
{

while (x==0)   //loop until condition is met (didn't write the condition yet, just testing)
{
std::cout << "Child process.\n\n";
std::cin >> messageWrite;
write(one[1], messageWrite, 256);
read(two[0], messageRead2, 256 );
}
}

else if(pid>0)  //father process
{
while(x==0)
{
std::cout << "Father process.\n\n";
std::cin >> messageWrite;
write(two[1], messageWrite2, 256);
read(one[0], messageRead, 256);
}
}
}

現在,兩個進程都來回移動,就像我想要的那樣,但它們都像這樣同時執行:

Father process.

Child process.

user input here
user input here
Father process.

Child process.
user input here
user input here
Child process.

Father process.
user input here
user input here

etc...

一種可以很好地工作的方法是,如果你試圖閱讀並且其中沒有任何東西,只需依靠管道阻塞。 使用它(在必要時配置),您可以定義一個進程來擁有您正在保護的資源,並且當它繼續擁有此資源時,它會根據需要使用它(並且管道為空)。

當資源所有者希望放棄資源時,它會將令牌寫入管道。 這個令牌可以是對你有意義的任何東西......一個簡單無意義的數據,或者具有意義的東西。

當任一進程希望擁有資源時(雖然它還沒有),它會讀取管道......這會阻塞它直到某些東西在那里。 當讀取成功時,該進程現在擁有該資源。

如果您擁有資源,只要在每個進程中跟蹤,就可以使用非阻塞I / O執行此操作。

您在問題中提供的代碼中的問題是兩個進程都立即寫入另一個進程,允許另一端的讀取成功而沒有任何延遲。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM