Skip to main content
BlogC Programming

Zombie Processes in Linux: a Better Understanding

By June 16, 2022September 12th, 2022No Comments

The term Zombie, makes it hard for use to think of Zombie Processes in Linux as anything other than a bad thing. The reality is quite different though, have hard it is to believe. Zombie Processes in Linux are a normal occurrence and created when a child process has completed. The parent process will start the child, the child does it thing and when it finishes it becomes zombie. This vital change indicates to the parent process that the child needs to be cleaned up or terminated. Of course, though, we should not see these zombies normally as they exist in this state for a small amount of time before being killed by the parent process. So it is likely that if we do see them then we have a badly written program. We going to use our own C program to allow us to see that this is a natural  state.


To illustrate zombies in Linux we can use a simple C program. The parent process will create a child process but then the parent sleeps. The child process ends immediately and goes into the zombie state. The parent sleeps for 300 seconds and will terminate the child on awakening.

#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main () {
  pid_t child_pid;
  child_pid = fork ();
  if (child_pid > 0) {
    sleep (300);
  }
  else {
    exit (0);
  }
  return 0;
}

We compile the code and execute in the background:

gcc -o zombie zombie.c
./zombie &

The command starts and the zombie will be there from the start:

$ ps -lf
F S UID PID PPID C PRI NI ADDR SZ WCHAN STIME TTY TIME CMD
0 S vagrant 1583 1582 0 80 0 - 2585 do_wai 07:36 pts/0 00:00:00 -bash
0 S vagrant 56923 1583 0 80 0 - 589 hrtime 16:05 pts/0 00:00:00 ./zombie
1 Z vagrant 56924 56923 0 80 0 - 0 - 16:05 pts/0 00:00:00 [zombie] <defunct>
0 R vagrant 56929 1583 0 80 0 - 2653 - 16:05 pts/0 00:00:00 ps -lf

We can also see this inside of the Linux cam top:

$ top -b -n1 -u $USER
top - 15:30:26 up 7:54, 1 user, load average: 0.01, 0.00, 0.00
Tasks: 108 total, 1 running, 106 sleeping, 0 stopped, 1 zombie
%Cpu(s): 0.0 us, 2.9 sy, 0.0 ni, 97.1 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
MiB Mem : 976.6 total, 139.2 free, 147.6 used, 689.8 buff/cache
MiB Swap: 1000.0 total, 998.7 free, 1.3 used. 654.0 avail Mem

PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
1507 vagrant 20 0 18352 7948 6468 S 0.0 0.8 0:00.04 systemd
1508 vagrant 20 0 169712 4236 0 S 0.0 0.4 0:00.00 (sd-pam)
1582 vagrant 20 0 13952 4296 2776 S 0.0 0.4 0:00.29 sshd
1583 vagrant 20 0 10340 5304 3336 S 0.0 0.5 0:00.13 bash
55205 vagrant 20 0 2356 580 512 S 0.0 0.1 0:00.00 zombie
55206 vagrant 20 0 0 0 0 Z 0.0 0.0 0:00.00 zombie
55250 vagrant 20 0 10868 3816 3236 R 0.0 0.4 0:00.00 top

The parent sleeps for 5 minutes and the parent will terminate the zombie before it exits itself.