Vivek Goel
Vivek Goel

Reputation: 24160

How to show error message when using flock if not able to get lock on the file

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

Answers (4)

me1960
me1960

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

loreb
loreb

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

vladz
vladz

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

Dima Chubarov
Dima Chubarov

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

Related Questions