What Unix commands can be made use of as a semaphore/lock?

I intend to run numerous Bash shell manuscripts in parallel. Nonetheless, I intend to stay clear of race problems. What Unix commands are absolutely atomic that I could make use of for this objective, and also just how can I utilize them?

0
2019-05-04 23:21:27
Source Share
Answers: 5

The system call mkdir() is atomic on POSIX filesystems. So, making use of the mkdir command as if it entails specifically one phone call to mkdir() would certainly attain your objective. (IOW, do not make use of mkdir -p). The equivalent unlock is rmdir certainly.

Caution emptor : mkdir() could not be atomic on network filesystems.

0
2019-05-08 23:21:20
Source

flock(1)

#!/bin/bash

# Makes sure we exit if flock fails.
set -e

(
  # Wait for lock on /var/lock/.myscript.exclusivelock (fd 200) for 10 seconds
  flock -x -w 10 200

  # Do stuff

) 200>/var/lock/.myscript.exclusivelock

This makes certain that code in between" (" and also ")" is run just by one procedure at once which the procedure does await a lock also long.

0
2019-05-08 11:46:04
Source

If lockfile is not mounted on your system, after that mkdir will certainly do the job : it's an atomic procedure, and also it falls short if the directory site currently exists (as long as you do not add the -p command - line button).

create_lock_or_wait () {
  path="$1"
  wait_time="${2:-10}"
  while true; do
        if mkdir "${path}.lock.d"; then
           break;
        fi
        sleep $wait_time
  done
}

remove_lock () {
  path="$1"
  rmdir "${path}.lock.d"
}
0
2019-05-08 10:38:42
Source

lockfile (1) resembles an excellent prospect, though beware that it's component of the procmail plan, which you might not have actually mounted on your equipment yet. It's a preferred adequate plan that it need to be packaged for your system if it's not mounted yet. 3 of the 4 systems I examined have it, and also the various other has it readily available.

Utilizing it is straightforward :

#!/bin/sh
LOCKFILE=$HOME/.myscript/lock
mkdir -p `dirname $LOCKFILE`

echo Waiting for lock $LOCKFILE...
if lockfile -1 -r15 $LOCKFILE
then
    # Do protected stuff here
    echo Doing protected stuff...

    # Then, afterward, clean up so another instance of this script can run
    rm -f $LOCKFILE
else
    echo "Failed to acquire lock!  lockfile(1) returned $?"
    exit 1
fi

The alternatives I've offered make it retry as soon as a 2nd for approximately 15 secs. Go down the" - r" flag if you desire it to wait for life.

0
2019-05-08 08:53:50
Source

Maybe the lockfile command will certainly do what you require.

lockfile ~/.config/mylockfile.lock
.....
rm -f important.lock
.
0
2019-05-08 06:09:53
Source