3

I'm running an app created using Spring boot. but for last sometimes i'm seeing it getting crashed. I am running this using nohup. I want to attach a hook to it, so that when this process stops a script runs that take backup out nohup.out and send out a mail to notify that server crashed. Is there anyway to do it?

NOTE: I guess this is not required but just for information. I am using ubuntu

1 Answers1

3

A clever approach presented by Kamil Maciorowski in this answer is to link the background app to its cleanup process simply my making them consecutive commands within one shell context.  A ‘simple’ way to do that would be

nohup sh -c "<Main Process>; <reporting process>" &

in which you asynchronously run a nohup’ed shell that runs the main process, and then runs the reporting/cleanup process (unconditionally) after the main process terminates (for any reason).  A more robust solution would be to write a short script:

#!/bin/sh
if <Main Process>
then
    <handling for normal termination>
else
    <handling for abnormal termination>
fi

or

#!/bin/sh
<Main Process>
case "$?" in
    ︙
esac

and then run the script with nohup foo.sh &

If your only concern is the app dying because of some internal error, this is probably the best solution.  If there is a risk of some other process going crazy and sending a bunch of lethal signals, then there is a possibility that the shell (that is waiting for the app to terminate) might also get blown away, and therefore be unable to start the cleanup process.  In that case, you might want to consider G-Man’s answer, which suggests having a monitoring process that sends a signal 0 to the app periodically.  If it gets an error indication that the process doesn’t exist any more, then it initiates the cleanup action.