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):
- then when I
kill -9 PID
, lockfile is deleted (ok) - 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
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 usekill
(without-9
) in the case where the trap worked? – ilkkachu Mar 22 '18 at 11:02