Operating System - HP-UX
1833750 Members
2562 Online
110063 Solutions
New Discussion

How to know when a background task has finished?

 
SOLVED
Go to solution
Kris Spander
Advisor

How to know when a background task has finished?

Hello experts,

Does anybody know how to determine if a background task is still running from a shell script?

TIA,
Kris

Dilbert is my hero.
4 REPLIES 4
Vasikaran Venkatesan
Frequent Advisor

Re: How to know when a background task has finished?

1) Pressing the enter (if the terminal was inactive after the bg job was started) - should say that "Job was Done"
2) ps -ef | grep -v grep | grep
A. Clay Stephenson
Acclaimed Contributor
Solution

Re: How to know when a background task has finished?

The standard method would be to send a kill -s 0 to the process and look at the result.

e.g.

mychild.sh &
CHILDPID=${!}
...
...
...
kill -s 0 ${CHILDPID} 2>/dev/null
STAT=${?}
if [[ ${STAT} -eq 0 ]]
then
echo "Child is still alive"
else
echo "It ain't"
fi

Plan B.
wait ${CHILDPID}

The parent will block until the designated child completes or
wait
the parent will block until all child processes have finished.

Plan C.
Just before the child process exits, have the child send a signal to the parent that the parent traps. This will allow the parent to continue processing asynchronously.

If it ain't broke, I can fix that.
Ulrich Deiters
Frequent Advisor

Re: How to know when a background task has finished?

Once you start the background task, the shell variable $! contains its PID. This can be used for automated checking, e.g.,

start_background_task
alive=`jobs -l | grep $! | wc -l`
if [ $alive -ne 1 ]
then
cleanup_after_bg_task
...

Steven E. Protter
Exalted Contributor

Re: How to know when a background task has finished?

you can also route the output through mailx -s

nohup scriptname & | mailx -s "job" me@my.net

the email will be delivered at job completion.

SEP
Steven E Protter
Owner of ISN Corporation
http://isnamerica.com
http://hpuxconsulting.com
Sponsor: http://hpux.ws
Twitter: http://twitter.com/hpuxlinux
Founder http://newdatacloud.com