不想立即删除终止子进程,需要成为僵尸

我从SE QUE获得以下信息明确地将SIGCHLD的处置设置为SIG_IGN会导致随后终止的任何子进程立即从系统中删除而不是转换为僵尸。

据我所知,要读取子状态,需要在进程表中使用子进程。 因此有必要在进程表中使用zombie子进程来读取子状态。

所以我想编写信号处理程序,它将删除“将SIGCHLD的处置设置为SIG_IGN”

我使用下面的代码(在fork之前)以避免在终止后立即删除子进程:但我仍然无法获得子状态并且waitpid使用ECHILD返回-1。

#include  #include  #include  #include  #include  #include  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; } } 

请提出一些想法,我被封锁了。

而不是捕获信号,只需在main中使用此代码:

 signal(SIGCHLD,SIG_IGN); 

而不是使用处理程序,使用SIG_IGN(如上所示)。 这忽略了信号和进程pid将保留在进程表中。然后,Parent可以使用waitpid()或wait()声明此僵尸进程的状态。