Operating System - HP-UX
1827293 Members
2359 Online
109717 Solutions
New Discussion

Re: korn shell scripting - how to check return codes of background processes?

 
SOLVED
Go to solution
Paul Ammirata
Occasional Contributor

korn shell scripting - how to check return codes of background processes?

I'm running a script that executes three processes (not necessarily shell script) in the background and then waits for them to complete. If any one of those processes exits with a non-zero return code I want to detect this and exit the script; otherwise I want to continue executing the script.

How can I do this? (i.e. check the return code of the completed background processes)

I've written the following test code, but I'm not able to detect any non-zero return codes.

#! /bin/ksh
# main script
backgroundprocess1 & #hardcoded to exit with 2
backgroundprocess2 & #hardcoded to exit with 0
backgroundprocess2 & #hardcoded to exit with 0
wait
echo $? # always displays 0

###################

#backgroundprocess1
sleep 5
exit 2

###################

#backgroundprocess2
sleep 5
exit 0

###################

#backgroundprocess3
sleep 5
exit 0
3 REPLIES 3
James R. Ferguson
Acclaimed Contributor
Solution

Re: korn shell scripting - how to check return codes of background processes?

Robin Wakefield
Honored Contributor

Re: korn shell scripting - how to check return codes of background processes?

Hi Paul,

A small word of caution - the wait in a korn-shell can give erratic results (see the last comment in James' link). If at all possible, use a bourne-shell, this gives 'sensible' results.

Rgds, Robin.
Bill Thorsteinson
Honored Contributor

Re: korn shell scripting - how to check return codes of background processes?

Consider writing a subroutine to execute a command
and record its status in a status file. Something like:

sub stat_command {
statfile=$1
shift
$($*; echo \$? > $statfile) &
}

You can then check the contents of the
statfiles when the tasks complete.