NeooeN NeooeN - 1 year ago 129
Linux Question

Detect when process quits or is being killed due out of memory

My bash script is running some program in background and with wait command waits for it to stop. But there is a high possibility that the background process will be killed because it takes too much memory. I want my script to react differently for a process that ended up gently and for a killed one. How do I check this condition?

Answer Source

Make sure your command signals success (with exit code 0) when it succeeds, and failure (non-zero) when it fails.

When a process is killed with SIGKILL by the OOM killer, signaling failure is automatic. (The shell will consider the exit code of signal terminated processes to be 128 + the signal number, so 128+9=137 for SIGKILL).

You then use the fact that wait somepid exits with the same code as the command it waits on in an if statement:

yourcommand &
if wait $pid
    echo "It exited successfully"
    echo "It exited with failure"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download