1

I've used flock a lot in the past to ensure that a process only spawns once (in case it gets hung up/etc) but I've never used it for two different processes.

In this scenario two different scripts affect the same "temp" directory (the dir is clobbered at the start of each run). So I need to ensure the temp dir is not clobbered by one script while another one is still needing it.

My goal:

  • Ensure 2 different scripts never execute alongside each other.

For example (cron sample):

0 * * * * flock -w 2 /tmp/lockfile.lock /some/script1.sh
2 * * * * flock -w 2 /tmp/lockfile.lock /another/script2.sh

Is this the correct way to isolate these two scripts from each other?

emmdee
  • 2,187
  • 12
  • 36
  • 60

2 Answers2

1

A DIY take on it could be to write a script, that would deal with your lock file, while eventually executing your job.

Say you create some /my/job executable, with the following:

#!/bin/sh

# to be tuned, at your convenience
LASTLOG=/tmp/job.log
LOCKFILE=/tmp/lockfile.lock
RETRY=3
WAIT=10
if test -z "$1"; then
    echo missing job script >&2
    exit 1
elif ! test -x "$1"; then
    echo can not execute "$1" >&2
    exit 1
fi
cpt=0
while test $cpt -lt $RETRY
do
    if ! test -s $LOCKFILE; then
        echo $$ >$LOCKFILE
        break
    fi
    sleep $WAIT
done
if ! grep ^$$$ $LOCKFILE >/dev/null 2>&1; then
    echo could not acquire lock >&2
    exit 2
fi
"$1" >$LASTLOG 2>&1
ret=$?

rm -f $LOCKFILE

exit $?

Then, your crontab would look like:

0 * * * * /my/job /some/script1.sh
2 * * * * /my/job /some/script2.sh
SYN
  • 1,751
  • 9
  • 14
1

There's this example in man flock on my Debian:

shell1> flock /tmp -c cat
shell2> flock -w .007 /tmp -c echo; /bin/echo $?
          Set exclusive lock to directory /tmp and the second command will fail.

So I gather the locking can be shared.

See more in the EXAMPLES section of man flock.