Question

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.

Was it helpful?

Solution

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"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top