您编写的代码与子叉一起同时运行fork()
。waitpid()
父级等到子级完成,通常只是为了获取从子级传递的数据并将其公开给父级。假设您运行一个主循环,其中任务作为“后台”运行。例如:
// a simple scheduler
while(1) {
if(done_task_1) {
// if done_task_1 is ever to change in the parent memory scope,
// parent must know the exit status of its child fork.
// otherwise there is no way to enter this if sentance, ever
collect_data_1();
run_task_1 = 0;
}
else if(run_task_1 == 1) {
// iterate instructions for a sec
posix_kill(pid_task_1, SIGCONT);
sleep(1);
posix_kill(pid_task_1, SIGSTOP);
}
if(done_task_2) {
collect_data_2();
run_task_2 = 0;
}
else if(run_task_2 == 1) {
// iterate instructions for a sec
posix_kill(pid_task_2, SIGCONT);
sleep(1);
posix_kill(pid_task_2, SIGSTOP);
}
if(run_task_1 == 0 && run_task_2 == 0) {
break;
}
}