5

This can be a very simple question but I don't understand why it behaves that way. When I invoke

lockfile-create --use-pid --retry 0 /tmp/my_lock_file

it returns 0, and next time it runs it returns some other code(4) as expected since it has already created the lock file. But when I wrap that same code in a bash script file, it always returns 0 as the exit code. Does someone know why it does not work?

Update: Complete bash file content

#! /bin/bash

LOCK=alert

lockfile-create --use-pid --retry 0 $LOCK
LOCK_CREATED=$?
echo "Lock file creation status $LOCK_CREATED"

and this is how I run it ./alert.sh.

Claudio
  • 10,614
  • 4
  • 31
  • 71
Bunti
  • 1,730
  • 16
  • 20
  • Do you have anything in the script other than this line? – Barmar Nov 20 '13 at 07:28
  • Then it should work as expected. The exit status of a script is the exit status of the last command it executed. – Barmar Nov 20 '13 at 07:32
  • #! /bin/bash LOCK=alert lockfile-create --use-pid --retry 0 $LOCK LOCK_CREATED=$? echo "Lock file creation status $LOCK_CREATED" is what is in the file. Sorry about cluttered formatting – Bunti Nov 20 '13 at 07:34
  • Please update your question, reading code in comments is difficult. – Barmar Nov 20 '13 at 07:34
  • Is a file named `alert` present in the current directory? Please note that `alert` and `alert.sh` will be different files though that doesn't seem to be the root of the problem. – Chandranshu Nov 20 '13 at 08:34

1 Answers1

3

But when I wrap that same code in a bash script file, it always returns 0 as the exit code.

This is because when you execute the script again, the PID of the process executing the script has changed. As such, the --use-pid flag causes lockfile-create into thinking that the lock file needs to be overwritten.

Depending upon your use case, you might want to get rid of the --user-pid flag. However, in that case you'd need to ensure that you clean up the lock file yourself.

Quoting from man lockfile-create:

   -p, --use-pid
       Write the parent process id (PPID) to the lockfile whenever a lock‐
       file  is created, and use that pid when checking a lock's validity.
       See the lockfile_create(3)  manpage  for  more  information.   This
       option  applies  to lockfile-create and lockfile-check.  NOTE: this
       option will not work correctly between machines sharing a  filesys‐
       tem.

You can verify the behaviour you're observing by attempting to create the log file again within the same script:

#! /bin/bash
LOCK=alert

lockfile-create --use-pid --retry 0 $LOCK
LOCK_CREATED=$?
echo "Lock file creation status $LOCK_CREATED"
lockfile-create --use-pid --retry 0 $LOCK
LOCK_CREATED=$?
echo "Lock file creation status $LOCK_CREATED"
devnull
  • 118,548
  • 33
  • 236
  • 227
  • Yes, Nice explanation. It solved my problems and I didn't want to use PID for any reason. Thanks devnull – Bunti Nov 20 '13 at 10:40