我的问题是我无法理解为什么这些代码仍然会生成僵尸进程。我该如何解决?谢谢。
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
int count = 0;
/**
* signal callback
* @param signo
*/
void sigcallback(int signo) {
short stime = 5;
int status;
wait(&status);
while (1) {
printf("wake up,%d\n", getpid());
sleep((stime + 1) - (short) (time(NULL) % stime));
}
}
int call_cmd(void) {
count++;
int i;
pid_t pid;
signal(SIGCHLD, sigcallback);
for (i = 0; i < 3; i++) {
if ((pid = fork()) < 0) {
printf("error with fork\n");
exit(1);
} else if (pid > 0) {
waitpid(pid, NULL, WNOHANG);
} else {
printf("\t\t\tsid is %d,count is %d,pid is %d\n", getsid(getpid()), count, getpid());
}
}
return 1;
}
void notice_root(int signo) {
printf("execut root signal\n");
waitpid(0, NULL, 0);
}
int main(void) {
pid_t pid;
int i;
signal(SIGCHLD, notice_root);
for (i = 0; i < 2; i++) {
if ((pid = fork()) < 0) {
printf("error with fork\n");
exit(1);
} else if (pid > 0) {
exit(0);
} else {
setsid();
call_cmd();
}
}
return 0;
}