问题描述
我从 SE QUE 中获得了以下信息将SIGCHLD的处置方式明确设置为SIG_IGN会导致随后终止的所有子进程立即从系统中删除,而不是转换为僵尸.
I got below information from SE QUEExplicitly setting the disposition of SIGCHLD to SIG_IGN causes any child process that subsequently terminates to be immediately removed from the system instead of being converted into a zombie.
据我所知,要读取子状态,需要在进程表中具有子pid.因此,必须在进程表中包含僵尸子进程以读取子状态.
As far I know, to read the child status it is required to have child pid in process table. So it is necessary to have zombie child process in process table to read the child status.
所以我想编写信号处理程序,该处理程序将删除将SIGCHLD的配置设置为SIG_IGN"
So I want to write signal handler which will remove "setting the disposition of SIGCHLD to SIG_IGN"
我使用以下代码(在fork之前)来避免在终止后立即删除子进程:但是我仍然无法获得子状态,并且waitpid用ECHILD返回-1.
I used below code (before fork) to avoid removal of child process immediately after termination: but still I am not able to get child status and waitpid returns -1 with ECHILD.
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
static siginfo_t sig_info;
static volatile sig_atomic_t sig_num;
static void *sig_ctxt;
static void catcher(int signum, siginfo_t *info, void *vp)
{
sig_num = signum;
sig_info = *info;
sig_ctxt = vp;
}
static void set_handler(int signum)
{
struct sigaction sa;
sa.sa_flags = SA_SIGINFO;
sa.sa_sigaction = catcher;
sigemptyset(&sa.sa_mask);
if (sigaction(signum, &sa, 0) != 0)
{
int errnum = errno;
fprintf(stderr, "Failed to set signal handler (%d: %s)\n", errnum, strerror(errnum));
exit(1);
}
}
static void prt_interrupt(FILE *fp)
{
if (sig_num != 0)
{
fprintf(fp, "Signal %d from PID %d\n", sig_info.si_signo, (int)sig_info.si_pid);
sig_num = 0;
}
}
请提出一些想法,对此我感到受阻.
Please suggest some idea, I am blocked with this.
推荐答案
代替捕获信号,只需在main中使用以下代码即可:
Instead of catching the signal ,just use this code in main :
signal(SIGCHLD,SIG_IGN);
而不是使用处理程序,请使用SIG_IGN(如上所示).这将忽略该信号,进程pid将保留在进程表中.然后,父级可以使用waitpid()或wait()声明此僵尸进程的状态.
Instead of using the handler, use SIG_IGN (as shown above) . This ignores the signal and process pid would remain in the process table .Parent can then claim the status of this zombie process using waitpid() or wait() .
这篇关于不想立即删除终止的子进程,需要成为僵尸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!