问题描述
我正在观察使用htop的进程,即使我使用waitpid调用进行清理,我仍然看到子进程保持僵尸状态。知道为什么会发生这种情况吗?
非常感谢您!
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <signal.h>
void child_signal_handler(int signal) {
printf("Someone is stabbed me with signal %d\n",signal);
}
int main(int argc,char** argv)
{
const pid_t child = fork();
if (child == 0) {
struct sigaction sa;
memset(&sa,sizeof(sa));
sa.sa_handler = &child_signal_handler;
sigaction(SIGTERM,&sa,NULL);
printf("Child is started in busy loop\n");
while (true)
;
} else {
const int mercy_period = 3;
printf("Parent is angry and gonna kill his child in %d sec\n",mercy_period);
sleep(mercy_period);
kill(child,SIGTERM);
// clean-up zombie child process as it is terminated before we can wait on
// it
int status = 0;
while(waitpid(-1,&status,WNOHANG) > 0);
}
return EXIT_SUCCESS;
}
解决方法
waitpid glibc实施注释
如果PID为(pid_t)-1,则匹配任何进程。如果在选项中将WNOHANG位置1,则该孩子 还没死,返回(pid_t)0。
由于_amazonses Pe82YD6rnCI0AXMHIZv8v0h/thYRZk97YCuQUA=
为假,因此while循环显然会立即退出。
将0 > 0
和信号更改为else
SIGKILL
几次尝试后,} else {
const int mercy_period = 3;
printf("Parent is angry and gonna kill his child in %d sec\n",mercy_period);
sleep(mercy_period);
kill(child,SIGKILL);
int status = 0;
pid_t pid = waitpid(-1,&status,WNOHANG);
while(!pid) {
pid = waitpid(-1,WNOHANG);
printf("%d\n",pid);
}
}
将返回子进程的pid。成功。