Skip to content

Instantly share code, notes, and snippets.

@blezek
Created October 29, 2012 19:49
Show Gist options
  • Save blezek/3976100 to your computer and use it in GitHub Desktop.
Save blezek/3976100 to your computer and use it in GitHub Desktop.

Revisions

  1. blezek revised this gist Oct 29, 2012. 1 changed file with 6 additions and 0 deletions.
    6 changes: 6 additions & 0 deletions lockit.sh
    Original file line number Diff line number Diff line change
    @@ -28,3 +28,9 @@ shlock() { _lock s; } # obtain a shared lock
    unlock() { _lock u; } # drop a lock

    ### BEGIN OF SCRIPT ###

    # Simplest example is avoiding running multiple instances of script.
    exlock_now || exit 1

    # Remember! Lock file is removed when one of the scripts exits and it is
    # the only script holding the lock or lock is not acquired at all.
  2. blezek created this gist Oct 29, 2012.
    30 changes: 30 additions & 0 deletions lockit.sh
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,30 @@
    #!/bin/bash

    ## Copyright (C) 2009 Przemyslaw Pawelczyk <[email protected]>
    ## License: GNU General Public License v2, v3
    #
    # Lockable script boilerplate

    ### HEADER ###
    hn=`hostname --short`
    LongHN=`hostname`

    mkdir -p $HOME/lock/$hn
    LOCKFILE="$HOME/lock/$hn/`basename $0`"
    LOCKFD=99

    # PRIVATE
    _lock() { flock -$1 $LOCKFD; }
    _no_more_locking() { _lock u; _lock xn && rm -f $LOCKFILE; }
    _prepare_locking() { eval "exec $LOCKFD>\"$LOCKFILE\""; trap _no_more_locking EXIT; }

    # ON START
    _prepare_locking

    # PUBLIC
    exlock_now() { _lock xn; } # obtain an exclusive lock immediately or fail
    exlock() { _lock x; } # obtain an exclusive lock
    shlock() { _lock s; } # obtain a shared lock
    unlock() { _lock u; } # drop a lock

    ### BEGIN OF SCRIPT ###