[英]why does this program create a zombie process and how do I fix it?
My question is I can't undertand why those code still generate zombie process. 我的问题是我无法承认为什么这些代码仍会生成僵尸进程。 how can I fixed it?
我怎么修好它? thanks.
谢谢。
#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;
}
You have an infinite sleep loop in your signal handler sigcallback
. 您的信号处理程序
sigcallback
有一个无限的睡眠循环。 Once a signal has been handled by that function, the process will never handle another SIGCHLD
signal again, since the signal handler never returns. 一旦该函数处理了一个信号,该进程将永远不再处理另一个
SIGCHLD
信号,因为信号处理程序永远不会返回。 This is likely the cause of your zombies. 这可能是你的僵尸的原因。
You do not get one signal delivered for every exited child. 您没有为每个退出的孩子提供一个信号。 If two children exit "simultaneously", you will only get a single
SIGCHLD
delivered. 如果两个孩子“同时”退出,您只能获得一个
SIGCHLD
。 So, when you wait in your signal handler (either of them), you should wait in a loop to reap all the children that have exited. 因此,当您在信号处理程序(其中任何一个)中等待时,您应该在循环中等待所有已退出的子项。 Something along the lines of:
有点像:
for (;;) {
pid_t p = waitpid(-1, 0, WNOHANG);
if (p <= 0) break;
/* ... */
}
When your process exits, the children of that process will be inherited by the init process, so they will be reaped properly. 当您的进程退出时,该进程的子进程将由init进程继承,因此它们将被正确地获取。 However, your infinite loop prevented 3 things:
然而,你的无限循环阻止了三件事:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.