Monday, August 17, 2015

double fork to avoid zombies

No, I'm not talking about our favorite villains. I am talking about orphaned computer processes that could end up as "zombie" processes when you look at "top" command results.

This is for IT aka nerdy types who do shell scripting in BASH or other major shells.

I initially found this method of avoiding process zombies somewhere on the internet. However, I just now searched for it and with small, but too much effort, I did not easily locate it again. --- Update --- I realized upon creating this post, that I had an unexplained example of this in my previous post "self-healing cron job".

So, here it is for future reference.

We wish to prevent creation of a zombie process, and we also wish our newly spawned process to be independent, in case we decide to close our shell.

This can be done in BASH using either nohup ... &, or ... Ctrl-z, disown.
A decent reference for this is here.

nohup YourCommandHere &

OR

YourCommandHere
Press Ctrl-z
disown

I don't recall all the advantages / disadvantages of the above methods. However, some day you may find yourself in a shell that is not BASH, that may not have the nohup and disown commands available.

This should work in all the major shells. It redirects all output to the "ether" commonly known as /dev/null by using 0<&- &>/dev/null. It also double forks and "disowns" using (( &) &). If I understand correctly, the reason for double instead of single fork is to make the newly created process 100% completely independent AND (this is important) force process id 1 to adopt the newly minted process. Process id 1 is god of everything on that computer, and will do all necessary management / clean up. That way, you can leave and go live on some beautiful island and forget about all your children. :) ----- (Please don't do this in your real life!)

(( YourCommandHere 0<&- &>/dev/null &) &)

Hope that helps somebody out there! It will help me, the next time I'm searching for it on Google.

2 comments:

  1. Why the hell doesn't searching for
    bash double fork avoid zombie
    in Google find this post?
    I have to say shell instead of bash for some reason like this:
    shell double fork avoid zombie

    ReplyDelete
    Replies
    1. For future reference, I should probably make a habit of searching for "shell" stuff instead of "bash" stuff.

      Delete

This is Charles Weldon Witt. Thank you for commenting on my blog.