1

I put my trap inside an if, run the script, and after that second execution, it warns that lock file is held (ok). But when I kill -9 the running PID, the lockfile is not removed.

When I move trap before the if (what you can see now commented below):

  1. then when I kill -9 PID, lockfile is deleted (ok)
  2. but when I run additional executions the scripts, only first one warns because after this first-additional run, the lockfile is removed by trap on EXIT!

How to get the trap inside if to remove the lockfile on kill -9 of the script?

lockfile=/tmp/localfile
#trap 'rm -f "$lockfile"; exit $?' INT TERM EXIT KILL
if ( set -o noclobber; echo "$$" > "$lockfile") 2> /dev/null;
then
    trap 'rm -f "$lockfile"; exit $?' INT TERM EXIT KILL
    while true
    do
        ls -ld ${lockfile}
        sleep 1
    done
    rm -f "$lockfile"
    trap - INT TERM EXIT
else
    echo "Failed to acquire lockfile: $lockfile."
    echo "Held by $(cat $lockfile)"
fi
1
  • if you shoot the script with SIGKILL, i.e. kill -9, it should be killed without getting a chance to react to the signal. Are you sure you didn't just use kill (without -9) in the case where the trap worked? Commented Mar 22, 2018 at 11:02

1 Answer 1

1

kill -KILL (or kill -9) kills the process without it being able to clean up. The SIGKILL signal is non-trappable by design.

Use a plain kill (sends TERM by default) instead.

See also: Why should I not use 'kill -9' / SIGKILL

4
  • thank you, I was thinking about a case that someone kills my process with -9 and the lock is not removed... Commented Mar 22, 2018 at 13:28
  • 1
    @DonJ If someone kills your script with SIGKILL, then you can't do anything to catch that. Commented Mar 22, 2018 at 13:42
  • Cleanup redundant lock files on initialisation? Ahh, how to determine if lock files are redundant? On a local-only app you should be able to detect if the process is already running or not but, what about a network application? network-root-user on each machine? Makes it complicated. Commented Mar 27, 2018 at 11:05
  • @Willtech Yes, the general case is not easy. Commented Mar 27, 2018 at 11:19

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.