Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I prevent zombie child processes?

I am writing a server that uses fork() to spawn handlers for client connections. The server does not need to know about what happens to the forked processes – they work on their own, and when they're done, they should just die instead of becoming zombies. What is an easy way to accomplish this?

like image 678
thejh Avatar asked Jun 10 '13 01:06

thejh


2 Answers

There are several ways, but using sigaction with SA_NOCLDWAIT in the parent process is probably the easiest one:

struct sigaction sigchld_action = {
  .sa_handler = SIG_DFL,
  .sa_flags = SA_NOCLDWAIT
};
sigaction(SIGCHLD, &sigchld_action, NULL);
like image 117
thejh Avatar answered Oct 10 '22 17:10

thejh


Use double forks. Have your children immediately fork another copy and have the original child process exit.

http://thinkiii.blogspot.com/2009/12/double-fork-to-avoid-zombie-process.html

This is simpler than using signals, in my opinion, and more understandable.

void safe_fork()
{
  pid_t pid;
  if (!pid=fork()) {
    if (!fork()) {
      /* this is the child that keeps going */
      do_something(); /* or exec */
    } else {
      /* the first child process exits */
      exit(0);
    }
  } else {
    /* this is the original process */  
    /* wait for the first child to exit which it will immediately */
    waitpid(pid);
  }
}
like image 25
xaxxon Avatar answered Oct 10 '22 17:10

xaxxon