Shell – Running multiple programs in the background and checking their return value

background-processscriptingshell

suppose I want to run a few (say, three) programs at once, like this

program1 & program2 & program3 &

if I want to know their pid's, I think the best way is to store them, like this

program1 &
pid1=$!
program2 &
pid2=$!
...

But now, what if I want to know if they have ended and if so, what value they returned? Something like this:

if [ program1 has ended ]; then
    do something with its return value
fi

Any help will be appreciated

Best Answer

# launch child process in background
launch_child_process &

# grab child's pid and store it (use array if several)
pid=$!

# later, wait for termination
wait $pid
# show return code from wait, which is actually the return code of the child
echo "Child return code:" $?

With several children, you can of course loop to wait on each pid and collect the corresponding return code. You get out of that loop when the last child ends.