我想用四个并行过程做一些事情
我首先分叉onec,再次在child和parent fork中获得4个进程。
我想要的是在完成所有4个过程之后做一些事情,所以我使用waitpid(-1, &status, 0);
我的理想输出是
in
numbers
out
但实际输出有时可能
in
numbers
out
one number
我无法理解。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <error.h>
int main()
{
pid_t cpid, w;
int status;
printf("%s\n", "in");
cpid = fork();
if (cpid == 0)
{
cpid = fork();
if (cpid == 0)
{
printf("%s\n", "1");
exit(EXIT_SUCCESS);
}
else{
printf("%s\n", "2");
exit(EXIT_SUCCESS);
}
}
else{
cpid = fork();
if (cpid == 0)
{
printf("%s\n", "3");
exit(EXIT_SUCCESS);
}
else{
printf("%s\n", "4");
//exit(EXIT_SUCCESS);
}
}
waitpid(-1, &status, 0);
printf("%s\n", "out");
//do something
exit(EXIT_SUCCESS);
return 0 ;
}
答案 0 :(得分:2)
您正在使用 pid = -1 的 waitpid()。它等待任何子进程完成。这意味着,只要子进程中的任何一个完成,父进程的 waitpid()就会退出。它不会等待任何其他子进程完成。
答案 1 :(得分:0)
处理场景的更好方法是在主进程中使用“SIGCHLD”的签名处理程序,并使用wait / waitpid获取子退出案例。在这种情况下,您的所有儿童死亡都可以被监控/通知,因为SIGCLD将被传递到主流程。