产生僵尸进程的情况是:子进程在父进程调用wait()函数之前结束。
以下代码可以产生僵尸进程:
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main ()
{
pid_t child_pid;
/* Create a child process. */
child_pid = fork ();
if (child_pid > 0) {
/* This is the parent process. Sleep for a minute. */
sleep (60);
}
else {
/* This is the child process. Exit immediately. */
exit (0);
}
return 0;
}
僵尸进程的父进程结束后会自动继承为父进程是init的子进程,init具有自动清除僵尸进程的能力。因此,当僵尸进程的亲夫进程终结后,僵尸进程也会立即被清除。
僵尸进程的消除,可以利用SIGCHLD信号,因为当一个子进程终止的时候,Linux会向它的父进程发送SIGCHLD信号。
以下代码掩饰如何利用此方法防止僵尸进程:
#include <signal.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
sig_atomic_t child_exit_status;
void clean_up_child_process (int signal_number)
{
/* Clean up the child process. */
int status;
wait (&status);
/* Store its exit status in a global variable. */
child_exit_status = status;
}
int main ()
{
/* Handle SIGCHLD by calling clean_up_child_process. */
struct sigaction sigchld_action;
memset (&sigchld_action, 0, sizeof (sigchld_action));
sigchld_action.sa_handler = &clean_up_child_process;
sigaction (SIGCHLD, &sigchld_action, NULL);
/* Now do things, including forking a child process. */
/* ... */
return 0;
}