Itération 122442
Itération 122442

Reputation: 2962

In bash, how to catch the "event" that the program exits itself?

I have a bash program that needs to remove a lock file whenever it terminates.

It does not matter if the bash exits at the end of execution or if it failed at some point and exits with an error code, I want to catch this event and do some stuff before it actually terminates for good.

I have read about trap, but if trap is the solution, I do not understand which signal should be given to trap in order to catch all "exits possibilities".

Is trap the solution ? If not, how can this be achieved ?

Upvotes: 0

Views: 301

Answers (1)

Jack
Jack

Reputation: 6158

Try something like

trap 'cleanup' EXIT

at the start, and have a function cleanup:

function cleanup()
{
    # Kill any lingering child processes
    # kill -9 $(jobs -p) 2> /dev/null
    kill -9 0 2> /dev/null
}

Upvotes: 1

Related Questions