Zombie and Orphan Process

这里记录了一下 orphan 和 zombie process 的区别和表现形式,以及在 bash 中怎么制造它们和处理 zombie.

Today after killing a running process, it didn’t get removed but was marked as <defunct> (run ps can see it). What’s this?

Zombie vs Orphan process On Unix and Unix-like computer operating systems, a zombie process or defunct process is a process that has completed execution but still has an entry in the process table. This entry is still needed to allow the parent process to read its child’s exit status.

Zombie processes should not be confused with orphan processes: an orphan process is a process that is still executing, but whose parent has died. When the parent dies, the orphaned child process is adopted by init (process ID 1). When orphan processes die, they do not remain as zombie processes; instead, they are waited on by init. The result is that a process that is both a zombie and an orphan will be reaped automatically.

To create orphan in bash:

1
2
3
4
5
# this subshell spawns a new process sleep in background
# and print the child pid then die immediately
(sleep 10 & echo orphan pid $!)
# now the ppid is took over by init process
ps axo pid,ppid,comm | grep <orphan pid>

Notice that & is background sign, don’t append ; after it.

To make zombie in bash:

1
2
3
(sleep 1 & echo zombie pid $!; exec /bin/sleep 60) &
# check <defunct> mark
ps axo pid,ppid,comm | grep <zombie pid>

Analysis: in subshell we first spawn sleep 1 on background and output the child pid, then we exec to replace the parent shell, so sleep 1 will not be reaped by the original parent, neither of init process because its parent does not die, thus become a zombie. Eventually they both are reaped by init.

There is no harm in letting such processes be unless there are many of them. Processes that stay zombies for a long time are generally an error and cause a resource leak, but the only resource they occupy is the process table entry – process ID.

To check the maximum number of process can be created:

1
cat /proc/sys/kernel/pid_max

Usually zombie process will last a very short time, it will be reaped by its parent or init as mentioned above. But if not, need to reap them manually.

I checked the PPID of that defunct process, it’s not PID 1 but other shell process. By killing its parent process, the zombie will be handed over to init and reaped. Just check the PPID:

1
2
3
ps axo pid,ppid | grep defunct
# or
ps -ef | grep defunct

You can also use this command to verify defunct process is gone.

Notice you cannot kill zombie because by kill -9 since it is already dead!

0%