Cross platform mutex to prevent script running more than instance?
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
import os, sys
mypid = os.getpid()
try: pid = int(open(lockfile).read())
except FileNotFoundError: pass
try: os.kill(pid, 0)
except OSError: pass
else: return False
print(mypid, file=open(lockfile, 'w'))
if not ok2run("/tmp/lockfile"): sys.exit(0)
D'Arcy J.M. Cain
Vybe Networks Inc.
IM:darcy at Vex.Net VoIP: sip:darcy at VybeNetworks.com