Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return value of background process

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.

like image 862
Anirudh Avatar asked Jul 18 '11 16:07

Anirudh


People also ask

How do I return a background process?

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.

How can I get exit status of background process?

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.


1 Answers

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
like image 57
evil otto Avatar answered Sep 23 '22 18:09

evil otto