Operating System - HP-UX
1834772 Members
3309 Online
110070 Solutions
New Discussion

using "wait PID" with >1 background process

 
SOLVED
Go to solution
Chris Baugh
Occasional Advisor

using "wait PID" with >1 background process

if >1 process is executed in background and wait is issued with the process ID of the first job, the return code from wait does not reflect the return code from the first job, so it seems. Is there any way of trapping this return code.

wait PID seems to work OK if there's only one background job executed
4 REPLIES 4
James R. Ferguson
Acclaimed Contributor
Solution

Re: using "wait PID" with >1 background process

Hi Chris:

Along the same lines as my response from your first post, run this:

#!/usr/bin/sh
#
/tmp/sh 1 &
P1=$!
/tmp/sh 2 &
P2=$!
#
echo "doing other work..."
sleep 10
echo $?
#
wait $P1
R1=$?
if [ "$R1" -ne 0 ]
then
echo "$P1 cannot continue $R1"
else
echo "$P1 ok $R1"
fi
#
wait $P2
R2=$?
if [ "$R2" -ne 0 ]
then
echo "$P2 cannot continue $R2"
else
echo "$P2 ok $R2"
fi
#
#_end.

#!/usr/bin/sh
#
#...this is /tmp.sh
sleep 2
exit $1 # return what was passed
#
#_end.

...JRF...
Don Bentz
Regular Advisor

Re: using "wait PID" with >1 background process

I'm confused about this script. My understanding was that '$!' returns the exit status of the last command NOT executed in the background(?)
Insecurity is our friend. It keeps you dependent.
Don Bentz
Regular Advisor

Re: using "wait PID" with >1 background process

Well my apologies and thanks to Mr. Ferguson. I haven't used '$?' for background processes because there is apparently an error in my book about '$?' (rather than $! as I originally responded). This is rather exciting actually. I have a lot of old scripts I can make modifications to. Thanks again.
Insecurity is our friend. It keeps you dependent.

Re: using "wait PID" with >1 background process

Be VERY careful about the return code you get from the wait command. It will only return the exit code of the process it waits on if the wait command is called BEFORE the process to be waited on exits.

e.g.
at a shell prompt:

$ sleep 10 &
which kicks off sleep in background

Now immediately enter

$ wait $!

when the wait returns enter:

$ echo $?

and you get a sensible return code

But try this:

$ sleep 10 &
which kicks off sleep in background

Now wait for 15 seconds, and then enter

$ wait $!

which will return immediately, then enter:

$ echo $?

and don't get a sensible return code!

This is a obviously an 'engineered' scenario, but this has caught me out in a script that 'waited' for a bunch of compresses to complete. The compresses exited immediately due to a badly constructed path name, but I spent ages looking for the odd return code I got out of wait!

I am an HPE Employee
Accept or Kudo