【发布时间】:2013-11-22 16:29:41
【问题描述】:
我相信有一种方法可以使用管道同步两个进程,但我不确定如何实现它。在我的代码中,子进程和父进程同时执行其代码,我希望一个进程等待另一个进程。例如,使用管道阻塞一个进程,直到另一个进程完成。
我的代码:
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)这样的多路复用系统调用,你应该阅读Advanced Linux Programming
标签: c++ linux unix process fork