How can I check the exit status of multiple proces

2019-08-03 07:54发布

问题:

I have a loop with a script in background

while read host
do
./script &
done
wait  #waits till all the background processes are finished

but i want to check the exit status of the proceess the how would i do it

while read host
do
./script &
wait $! || let "FAIL+=1"
done
wait
echo $fail

But the will the above code execute parallely because time is an important factor for me so i want to have parallel execution for all hosts.

Is this possible to know which process failed so that i can do

   echo "these are the list of process ids in background that failed"
   12346
   43561
   .....

And is there any limit to the number of parallel proceses that can be run in background. is it safe to run about 20 parallel proceses in the above loop

回答1:

You can add this to the end of your script:

RC=$?
test $RC -eq 0 || echo "$$ failed"
exit $RC

$$ returns the PID of the shell. Your backgrounded scripts will run in their own separate shells.

The exit $RC line is obviously optional.