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.
You could nest the background process inside a script. For example, if the process you wish to send to the background is called foo:
Then just run the above script in the background instead of
foo. you can kill it if you need to shut it down, but otherwise it will never terminate as long asfoocontinues to run, and if foo dies, you can do whatever you want to based on its error code.