Cross platform mutex to prevent script running more than instance?

D'Arcy Cain darcy at VybeNetworks.com
Mon Sep 3 12:15:17 EDT 2018


On 09/03/18 09:45, Malcolm Greene wrote:
> Use case: Want to prevent 2+ instances of a script from running ...
> ideally in a cross platform manner. I've been researching this topic and
> am surprised how complicated this capability appears to be and how the
> diverse the solution set is. I've seen solutions ranging from using
> directories, named temporary files,  named sockets/pipes, etc. Is there
> any consensus on best practice here?

Here's my simple method which works in pure Python so I guess that makes
it cross-platform.  Well, as long as it has process IDs anyway.  There's
a small window between reading the file and writing the new one but for
most purposes that should be OK.  If you have to worry about those
nano-second situations you will need to use one of those more
complicated methods.

import os, sys

def ok2run(lockfile):
    mypid = os.getpid()

    try: pid = int(open(lockfile).read())
    except FileNotFoundError: pass
    else:
        try: os.kill(pid, 0)
        except OSError: pass
        else: return False

    print(mypid, file=open(lockfile, 'w'))
    return True

if not ok2run("/tmp/lockfile"): sys.exit(0)

-- 
D'Arcy J.M. Cain
Vybe Networks Inc.
http://www.VybeNetworks.com/
IM:darcy at Vex.Net VoIP: sip:darcy at VybeNetworks.com



More information about the Python-list mailing list