Today I was writing an application under Ubuntu Linux where I wanted the user to be able to click on a shell script to start running the main C++ application as a daemon in the background. I found a few example scripts using the nohup and disown commands but none of them seemed to work and my application would terminate as soon as the shell window closed. I found that it was necessary to include a sleep command between spawning the process and using the $! result for the disown command.
A few of the example scripts I found didn’t include a sleep and seemed to be parts of well tested and documented packages so maybe this requirement varies by Linux distros. The following is the latter segment of the bash shell script I wrote:
nohup $INSTALLDIR/myapp </dev/null >>$INSTALLDIR/myapp.log 2>&1 & sleep 1 NEWPID=$! disown $NEWPID exit 0