Reputation: 24160
My bash code look likes:
set -e
(
flock -n 9
main $@
) 9>/var/lock/mylockfile
But currently it don't show any error message, if it is not able to get lock on the file. Is there a way to show error message ?
Upvotes: 2
Views: 4444
Reputation: 77
My solution:
lock="/tmp/name_of_lockfile.lck"
echo "Lockfile $lock"
exec 200>$lock
/usr/bin/flock -n --verbose 200 || exit 1
So when running succesfull
Lockfile /tmp/name_of_lockfile.lck
flock: getting lock took 0.000006 seconds
and not succesfull
Lockfile /tmp/name_of_lockfile.lck
flock: failed to get lock
Upvotes: 0
Reputation: 1357
The example in the manpage says:
(
flock -n 9 || exit 1
# ... commands executed under lock ...
) 9>/var/lock/mylockfile
ie it exits if flock fails -- why don't you just use that? If you want to display an error, you could try this:
(
# paranoia: flock may fail with an exit code other than 1,
# eg if it can't be found in $PATH
if flock -n 9 ; then
do_stuff
else
show_error
fi
) 9>$lockfile
Upvotes: 3
Reputation: 327
With "set -e", you can use the ERR signal. As said in the man page of bash (description of the "set" command with option "-e"):
"A trap on ERR, if set, is executed before the shell exits."
So you can try something like:
set -e
(
trap 'echo flock failed.' ERR
flock -n 9
trap - ERR # reset ERR trap
main $@
) 9>/var/lock/mylockfile
Upvotes: 2
Reputation: 17179
You should check for the return code of flock -n
set -e
(
flock -n 9
if [ "$?" -eq 1 ] ; then
echo "could not lock"
exit 1
fi
main $@
) 9>/var/lock/mylockfile
Upvotes: 1