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.