Skip to content

Instantly share code, notes, and snippets.

@jeffreyiacono
Last active October 12, 2015 12:58
Show Gist options
  • Save jeffreyiacono/4030296 to your computer and use it in GitHub Desktop.
Save jeffreyiacono/4030296 to your computer and use it in GitHub Desktop.
a sample script that sleeps
# round 1! => nonblocking example
[process a] $ flock -en sleeper.lock ./sleeper.sh
time to sleep ...
[process b] $ flock -en sleeper.lock ./sleeper.sh
# ^ will exit b/c of n switch: "Fail (with an exit code of 1)
# rather than wait if the lock cannot be immediately acquired.
... waking up # <= process a returning
# round 2! => blocking example
[process a] $ flock -en sleeper.lock ./sleeper.sh
time to sleep ...
[process b] $ flock -e sleeper.lock ./sleeper.sh
# ^ will wait for the lock to become available b/c not using -n this time
... waking up # <= process a returning
time to sleep ... # <= process b executing sleeper.sh
... waking up # <= process b returning
# round 3! => different lock example
[process a] $ flock -en sleeper.lock ./sleeper.sh
time to sleep ...
[process b] $ flock -en different-sleeper.lock ./sleeper.sh
time to sleep ...
... waking up # <= process a returning
... waking up # <= process b returning
# ^ process b runs without waiting because flock is not using the same
# lock file to ensure a lock. Take away: lockfile names matter!
# round 4! => locks are advisory only
[process a] $ flock -en sleeper.lock ./sleeper.sh
time to sleep ...
[process b] $ ./sleeper.sh
time to sleep ...
... waking up # <= process a returning
... waking up # <= process b returning
# ^ process b runs without waiting because it didn't use flock
# locking is only advisory and will not do anything if
# flock is not always used.
#!/bin/bash
# All this script does it announce it's going to sleep,
# sleeps, and then announces when it wakes back up
echo "time to sleep ..."
sleep 10
echo "... waking up"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment