The return value of the background process

I need to take some action based on the return value of the background process, i.e. if it completes first.

In particular: in perfect work, the server that I run as a background process will continue to work forever. In such cases, saving in the background makes sense, since I want my shell script to do other things after the server spawns. But if the server fails abnormally, I want to preferably use the return value from the server to decide whether to kill my main script or not. If this is not possible, I at least want to interrupt the main script, and not run it with a failed server.

I am looking for something in the nature of asynchronous callbacks for shell scripts. One solution is to create a monitoring process that periodically checks whether the server has failed or not. Preferably, I would like to do this without this in the most basic shell script.

+6
source share
3 answers

You can nest the background process inside the script. For example, if the process you want to send to the background is called foo:

#!/bin/sh foo if [ $? ] then # do something here if process failed fi 

Then just run the above script in the background instead of foo . you can kill it if you need to close it, but otherwise it will never end while foo continues to work, and if foo dies, you can do whatever you want based on the error code.

-2
source

You can use shell traps to call functions when the child completes the SIGCHLD capture. If only one background process is running, you can wait for it in the sigchld handler and get the status there. If several background children work, it becomes a little more complicated; here is a sample code (tested only 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 
+2
source

I like that the first is better for my purpose, I believe that "do something here if the process failed." I can kill the script that called this shell script for foo using this name.

I think the first solution works well for several children. Anyway, I needed to do this quickly, so I used a hack that works for my application:

I run the process in the background, as usual, basically a script, and then use $! to get its pid (since $! returns the last bg pid), sleep for 2 seconds and do ps -e | grep pid to check if the whole process is based on the return value (ps -e | grep pid). This works well for me, because if my background process is interrupted, it does it immediately (because the address is being used).

0
source

Source: https://habr.com/ru/post/893002/


All Articles