我相信有一种方法可以使用管道同步两个进程,但我不确定如何实现它。在我的代码中,子进程和父进程同时执行它的代码,我希望一个进程等待另一个进程。例如,使用管道阻塞一个进程,直到完成其他进程。如何使用管道同步父级和子级进程?
我的代码:
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...
您可能会考虑使用[poll(2)](http://man7.org/linux/man-pages/man2/poll.2.html)等多路复用系统调用,您应该阅读[高级Linux编程]( http://advancedlinuxprogramming.com/) –