Tuesday, June 18, 2013

UNIX/LINUX HOW TO KILL A ZOMBIE PROCESS

What is a zombie process? ( Z state process)

When a process ends/dies, it becomes a zombie. Process will be in zombie state, till its exit status and data will be received by its parent..

When a child process dies, its parent is informed by the SIGCHLD signal.. So when this happens, Parent process should execute wait() system call to receive its child's return.

Till parent process execute this wait system call, its child waits in zombie state.

In zombie state, there will be no resource consumption actually.. Only process information remain in memory, kernel tables..

Following is an example for a parent that leaves its processes in zombie state for a certain time...

Look; it forks, and then syncronously waits for its child processes..


#include <sys/wait.h>
#include <stdlib.h>
#include <unistd.h>
int main(void)
{
pid_t pids[10];
int i;
for (i = 9; i >= 0; --i) {
pids[i] = fork();
if (pids[i] == 0) {
sleep(i+1);
_exit(0);
}
}

for (i = 9; i >= 0; --i)
waitpid(pids[i], NULL, 0);
return 0;
}

How to kill a zombie process?

kill -9 will not kill a zombie process..

With kill -9 , SIGKILL signal is sent to the desired process. This signal cannot be caught by the process, because it s not even sent to the process, it s handled by the kernel..

For zombie processes, by design, kernel will not kill the process, as actually this process is not living, process is only appearing in ps ..

So wait system call is needed here and the wait system call is commonly invoked in the SIGCHLD handler..


static void sigchld_hdl (int sig)
{
/* Wait for all dead processes.
* We use a non-blocking call to be sure this signal handler will not
* block if a child was cleaned up in another part of the program. */
while (waitpid(-1, NULL, WNOHANG) > 0) {
}
}

So we use/try "kill -s SIGCHLD" .. By sending SIGCHLD signal to the parent process, we make the parent process to issue wait() and clear its zombie processes. .

If parent process can't process or ignores the signal, zombie processes will not be cleared..
In such situations, killing the parent process will make the init process to take over the child ownership
,issue the wait call and clear the zombie processes... As it is known that, Init process periodically issue the wait system call.. 


No comments :

Post a Comment