Friday, May 3, 2013

Killing orphans and zombies

First please do not misunderstand me about "killing orphans and zombies". I'm for sure not going to hurt people without parents or people that are already dead :-(
I'm talking about running processes that can be harmful for your system and shuld be better get killed.

First of all a Zombie process is not an orphan process. As the word says, an orphan process is a procees without legitim parent, a zombie process is not alive but still have an entry in parent table.
A process can be orphaned either intentionally or unintentionally. Sometime a parent process exits/terminates or crashes leaving the child process still running, and then they become orphans.
In Linux/Unix like operating systems, as soon as parents of any process are dead, re-parenting occurs, automatically. Re-parenting processes whose parents are dead, means Orphaned processes, are immediately adopted by special process "init".

Take a look to a htop situation where winexe causes a lot of orphan processes:



An orphan process is a user process, which is having init (process id - 1) as parent. You can use this command in linux to find orphan processes.

       
ps -elf | head -1; ps -elf | awk '{if ($5 == 1 && $3 != "root") {print $0}}' | head


I've added an extra condition to awk cause i want to find orphan processes caused by winexe ( I added thus  && match($15,'winexe-1.00') )

       
ps -elf | head -1; ps -elf | awk '{if ($5 == 1 && $3 != "root" && match($15,'winexe-1.00')) {print $0}}' | head


I get now only the PID of the orphan process ( see in the commad {print $4} instead of {print $0}; we also leave the | head away )

       
ps -elf | ps -elf | awk '{if ($5 == 1 && $3 != "root" && match($15,'winexe-1.00')) {print $4}}'


Then I kill the processes (root permissions required, see sudo before xargs kill -9)

       
ps -elf | ps -elf | awk '{if ($5 == 1 && $3 != "root" && match($15,'winexe-1.00')) {print $4}}' | sudo xargs kill -9


You can put the last command line in a root cron job (without sudo before xargs kill -9) and let it run for instance once per hour.