</>EmbeddedInterview

What is a zombie process and an orphan process?

EasyOperating System Concepts

Short answer: A zombie is a process that has exited but whose parent has not yet called wait() to collect its exit status, so its entry stays in the process table. An orphan is a process whose parent has exited while it is still running; the kernel re-parents it to init (PID 1) or to a "subreaper", which will reap it when it exits.

Zombies

  • After exit(), the kernel frees the memory and files but keeps a small record (PID, exit status, resource usage) so the parent can ask for it.
  • ps shows state Z and <defunct>.
  • A few short-lived zombies are normal. Many zombies mean the parent never calls wait(); they use PIDs and can eventually stop new processes from being created.
  • You cannot kill a zombie, it is already dead. Fix or kill the parent; init then adopts and reaps the zombies.

Preventing zombies in the parent

#include <signal.h>
#include <sys/wait.h>
#include <errno.h>

static void on_sigchld(int sig)
{
    int saved = errno;
    while (waitpid(-1, NULL, WNOHANG) > 0)   /* reap all finished children */
        ;
    errno = saved;
}

/* in main(): */
struct sigaction sa = { .sa_handler = on_sigchld, .sa_flags = SA_RESTART | SA_NOCLDSTOP };
sigaction(SIGCHLD, &sa, NULL);

Or set SIGCHLD to SIG_IGN, which tells the kernel to reap children automatically (you then cannot get their exit status).

Orphans

  • Not a problem in themselves: daemons are often deliberately orphaned (the classic double-fork) so they are adopted by init.
  • prctl(PR_SET_CHILD_SUBREAPER) lets a service manager (systemd, container runtimes) adopt orphans of its own children instead of PID 1.

Interview follow-up: "What happens if PID 1 does not reap?" Zombies accumulate system-wide. This is a real problem in containers where the application runs as PID 1 and was not written to reap children; tini or dumb-init solve it.