I need to take some action based on the return value of a background process ie if it terminates in the first place.
Specifically : in ideal operation, the server which I run as the background process will just keep running forever. In such cases keeping it in the background makes sense, since I want my shell script to do other things after spawning the server. But if the server terminates abnormally, I want to preferably use the exit return value from the server to decide whether to kill my main script or not. If that's not possible I at least want to abort the main script rather than run it with a failed server.
I am looking for something in the nature of an asynchronous callback for shell scripts. One solution is to spawn a monitoring process that periodically checks if the server has failed or not. Preferably I would want to do it without that within the main shell script itself.
2: Using CTRL + Z, bg command. You can then use the bg command to push it to the background. While the process is running, press CTRL + Z. This returns your shell prompt. Finally, enter the bg command to push the process in the background.
To know what process has terminated and which was its exit code, we need to use the parameters -n and -p. With -n, we tell wait to return when any PID has terminated, without waiting for all of them. With -p, we specify a variable name where the PID is store.
You can use shell traps to invoke a function when a child exits by trapping SIGCHLD. If there is only one background process running, then you can wait
for it in the sigchld handler and get the status there. If there are multiple background children running it gets a little more complex; here is a code sample (only tested with bash):
set -m # enable job control
prtchld() {
joblist=$(jobs -l | tr "\n" "^")
while read -a jl -d "^"; do
if [ ${jl[2]} == "Exit" ] ; then
job=${jl[1]}
status=${jl[3]}
task=${jl[*]:4}
break
fi
done <<< $joblist
wait $job
echo job $task exited: $status
}
trap prtchld SIGCHLD
(sleep 5 ; exit 5) &
(sleep 1 ; exit 7) &
echo stuff is running
wait
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With