Friday, 11 July 2014

setsid Unix command to the rescue!

Assuming you have a main script, which is running a few other scripts in nohup in the background, and at the end, you want to run "tail -f" for the log file in a loop, until done.
If you press Ctrl-C, the main script will die, together with all the other scripts running in nohup, not exactly the desired result.

For example:

Main.sh:

nohup ./script1  > ${NOHUP_FILE1} 2>&1 &
nohup ./script2  > ${NOHUP_FILE2} 2>&1 &

RUN_IND=0
while [ $RUN_IND -eq 0 ]  ; do
ps -ef |grep Main |grep -v grep  > /dev/null
RUN_IND=$?
tail  -5   ${NOHUP_FILE1}
sleep 5
done

The solution will be to replace nohup by setsid, as below:

Main.sh:

setsid./script1  > ${NOHUP_FILE1} 2>&1 &
setsid./script2  > ${NOHUP_FILE2} 2>&1 &

RUN_IND=0
while [ $RUN_IND -eq 0 ]  ; do
ps -ef |grep Main |grep -v grep  > /dev/null
RUN_IND=$?
tail  -5   ${NOHUP_FILE1}
sleep 5
done


1 comment:

  1. Actually I ran into the lonk below during my research, which explains the same issue:

    http://superuser.com/questions/708919/ctrlc-in-a-sub-process-is-killing-a-nohuped-process-earlier-in-the-script

    ReplyDelete