【发布时间】:2021-01-13 00:32:54
【问题描述】:
在下面的代码中,我创建了 3 个子进程。我想让父母先完成[some code 1],然后让父母和3个孩子同时继续,等所有孩子都死了再继续[some code 3]。
但显然,在运行代码时,有时孩子会在发送 SIGSTOP 之前启动自己的[some code x]。现在我不允许使用sleep()。我可以做些什么来确保孩子在父母完成[some code 1]之前等待?
pid_t fpid1 = fork();
if (fpid1 > 0) { // parent
kill(fpid1, SIGSTOP);
pid_t fpid2 = fork();
if (fpid2 > 0) { // parent
kill(fpid2, SIGSTOP);
pid_t fpid3 = fork();
if (fpid3 > 0) { // parent
kill(fpid3, SIGSTOP);
[some code 1];
kill(fpid1, SIGCONT);
kill(fpid2, SIGCONT);
kill(fpid3, SIGCONT);
[some code 2];
while(wait(NULL) > 0);
[some code 3];
}
else if (fpid3 == 0) { // child 3
[some code 4];
exit(0);
}
}
else if (fpid2 == 0) { // child 2
[some code 5];
exit(0);
}
}
else if (fpid1 == 0) { // child 1
[some code 6];
exit(0);
}
【问题讨论】:
标签: c linux process operating-system multiprocessing