Test if Script Already Running

Cameron Simpson cs at zip.com.au
Thu Apr 20 00:27:33 EDT 2017

On 18Apr2017 19:31, Matt <matt.mailinglists at gmail.com> wrote:
>I have a number of simple scripts I run with cron hourly on Centos
>linux.  I want the script to check first thing if its already running
>and if so exit.
>In perl I did it with this at the start of every script:
>    use Fcntl ':flock';
>    INIT {
>        open LH, $0 or die "Can't open $0 for locking!\nError: $!\n";
>        flock LH, LOCK_EX | LOCK_NB or die "$0 is already running somewhere!\n";
>    }
>How can I do something like this in Python?

Others have pointed the way to an exact implementation.

For myself, I like mkdir. It is portable. It is atomic. It fails if the target 
exists.  It works over NFS etc. It is easy.

  ... do stuff ...

and it is equally doable in a shell script (eg your cron job):

  if mkdir lockdir
    ... do stuff ...
    rmdir lockdir
    echo "lockdir already takens, aborting" >&2
    exit 1

which means you don't need to fit the lock logic inside every tool, you can 
just do it in the script that calls them.

Cameron Simpson <cs at zip.com.au>

More information about the Python-list mailing list