I try to start 100 processes at the same time in the following code:
int cnt = 0;
void sig_handler(int signo) {
pid_t pid;
int stat;
pid = wait(&stat);
cout << "cnt:" << ++cnt << ", pid:" << pid << " signal:" << signo << endl;
}
int main() {
signal(SIGCHLD, sig_handler);
for (int i = 0; i < 100; ++i) {
if (fork() == 0) {
sleep(1);
exit(0);
}
}
printf("wait\n");
while (1);
}
I catch the SIGCHLD
signal in sig_handler
, the results are different: sometimes all processes return OK; sometimes 1 to 4 processes become zombies.
[vinllen@my-host]$ ./a.out
wait
cnt:1, pid:4383 signal:17
cnt:2, pid:4384 signal:17
cnt:3, pid:4385 signal:17
cnt:4, pid:4386 signal:17
cnt:5, pid:4387 signal:17
…
cnt:94, pid:4476 signal:17
cnt:95, pid:4477 signal:17
cnt:96, pid:4478 signal:17
cnt:97, pid:4479 signal:17
cnt:98, pid:4480 signal:17
[vinllen@my-host ~]$ ps aux | grep a.out
Vinllen 4382 96.2 0.0 13896 1084 pts/8 R+ 15:14 0:03 ./a.out
Vinllen 4481 0.0 0.0 0 0 pts/8 Z+ 15:14 0:00 [a.out] <defunct>
Vinllen 4482 0.0 0.0 0 0 pts/8 Z+ 15:14 0:00 [a.out] <defunct>
Vinllen 4493 0.0 0.0 105300 864 pts/9 S+ 15:14 0:00 grep a.out
I guess the reason is more than one processes exit at the same time and trigger something. Could anyone give me the detailed reason and tell me how to solve this problem.
In my understanding, double fork and ignore SIGCHLD are two effective ways to solve this problem. However, how to solve in this code that still calling wait
.