exit-post-hook-unlock.sh: use a trap to release the lock
[experiments/hook-lock.git] / exit-post-hook-unlock.sh
1 #!/bin/sh
2 #
3 # Example of how to safely release the lock in the "post" hook.
4 #
5 # Copyright (C) 2018  Antonio Ospite <ao2@ao2.it>
6 # SPDX-License-Identifier: WTFPL
7 #
8 # This program is free software. It comes without any warranty, to
9 # the extent permitted by applicable law. You can redistribute it
10 # and/or modify it under the terms of the Do What The Fuck You Want
11 # To Public License, Version 2, as published by Sam Hocevar. See
12 # http://sam.zoy.org/wtfpl/COPYING for more details.
13
14 set -e
15
16 LOCKDIR=/run/lock/mylockdir
17 [ -d "$LOCKDIR" ] || exit 0
18
19 LOCKPID=$(cat "$LOCKDIR/pid")
20 [ "$LOCKPID" = $PPID ] || { echo "The enter script was launched from another process. Unlocking aborted." >&2; exit 1; }
21
22 # Use a trap to release the lock even if the commands below fail.
23 trap 'rm -rf "$LOCKDIR"' EXIT
24 trap 'exit 2' HUP INT QUIT PIPE TERM
25
26 # Do stuff here.