如果我运行这个程序,我会有失效的进程吗?我正在尝试创建一个主程序,该程序并行运行 5 个进程,然后不获取已失效的进程。麻烦主要是要确保这不会发生。我不太确定我到目前为止是否做得对。我听说这是一个很好的做法,通过让你的进程“wait()”来确保你的进程没有失效的进程,以确保尽可能多的孩子已经被“fork()”了。
#include <time.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
void forkChildren(int nrofChildren, int *nr_of_children) {
pid_t pid;
int i;
for(i=0; i<5; i++) {
/* fork a child process */
pid = fork();
(*nr_of_children)++;
/* error occurred */
if (pid < 0) {
fprintf(stderr, "Fork failed\n");
exit(-1);
}
/* successful child */
else if (pid == 0) {
int sleeptime=1; //rand()%10;
printf("I am child: %d \nwith parent: %d \nin loop: %d \nand will sleep for: %d sec\n\n", getpid(), getppid(), i, sleeptime);
sleep(sleeptime);
printf("Ending of child: %d \nwith parent :%d in loop: %d\n\n", getpid(), getppid(), i);
}
/* parent process
else {
wait(NULL); Do I need this to make sure I dont get defunct processes???
} */
}
}
int main(int argc, char *argv[]) {
srand((unsigned int)time(NULL));
int nr_of_children=0;
if (argc < 2) {
/* if no argument run 5 childprocesses */
forkChildren(5, &nr_of_children);
} else {
forkChildren(atoi (argv[1]), &nr_of_children);
}
wait(NULL);
printf("End of %d, with %d nr of child-processes\n\n", getpid(), nr_of_children);
return 0;
}