【发布时间】:2015-06-11 03:38:22
【问题描述】:
我正在 fork() 并创建 4 个同时运行的子进程(做一个忙碌的工作),但父进程需要等到所有子进程退出。 我觉得我可以用更好的方式对其进行编码.. 有什么建议或者看起来还可以吗? (我需要保持这种格式的 2 功能和主要)
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;
}
【问题讨论】:
-
这篇文章很适合codereview.stackexchange.com