我在fork()ing并创建同时运行的4个子进程(忙碌的工作),但是父级需要等待所有子级退出。
我觉得我可以用更好的方法编写代码。.有什么建议吗?看起来还好吗? (我必须保持2个函数和main的这种格式)
using namespace std;
void simulateBusyWork(char, pid_t);
pid_t performFork();
int main()
{
srand(time(NULL));
performFork();
return 0;
}
pid_t performFork() {
pid_t pid;
//create four child processes
for (int i = 0; i < 4; ++i) {
pid = fork();
if (pid<0) {
continue;
} else if (pid == 0) {
break;
}
}
//fork failed
if (pid < 0) {
fprintf(stderr, "Fork failed./n");
return 1;
}
//child process do busy work
else if (pid == 0) {
cout << "A child process with PID " << getpid() << " was created." << endl;
pid = getpid();
simulateBusyWork('C', pid);
_exit(0);
}
//parent process do busy work
else if(pid > 0){
simulateBusyWork('P', getpid());
//parent process waits for children to exit
int status, exited;
//print which child has exited
for (int i = 0; i < 4; i++) {
exited = waitpid(-1, &status, 0);
cout << "P" << getpid() << ": Process " << exited << " has exited." << endl;
}
}
return pid;
}
void simulateBusyWork(char ch, pid_t pid) {
for (int i=0 ; i < 4; i++) {
cout << ch << pid << ": " << i << endl;
//if (i < 4)
sleep(1);
}
cout << "Process " << ch << pid << " has finished its work." << endl;
}
最佳答案
man waitpid
:
呼叫wait(&status)
是等效的
至:
waitpid(-1, &status, 0);
因此您可以简化一下。