Single Instance of app

Tim Hammerquist tim at vegeta.ath.cx
Mon Aug 27 01:45:42 EDT 2001


Me parece que Peter Hansen <peter at engcorp.com> dijo:
> Tim Hammerquist wrote:
> > 
> > import os
> > user_dir = getuserdir()  # dunno how this is done on WinNT/2000
> > lock_filename = user_dir + 'lock'
> > if os.path.exists(lock_filename):
> >     print "process already running"
> >     sys.exit(1)
> > lock_file = open(lock_filename, 'w')
> > lock_file.write("%d\n" % os.getpid())
> > lock_file.close()
> > # go on about business as usual
> > 
> > This has worked for decades on *nix. <wink>  If it doesn't work on your
> > OS, I'd like to know how you end up solving the problem.
> 
> Are you certain *that* particular pattern has worked for decades?
> It looks like it has a classic synchronization problem, when 
> two processes are started simultaneously and they both make it
> past the os.path.exists() line before either executes the open()
> statement.  Or is this just a risk people live with?

It was never intended to be production-quality code. It was an ad-hoc
script thrown together to (roughly) illustrate one method of lockfiles
on Unix systems.

In retrospect, I should have directed the OP to a place to read more
about this. However, I'm not in the mood at the moment to give the OP
the _exact_ code _for_ him.

On that note, one should obtain a lock on the target file before
assuming as much about it as my above code did. The fcntl module is
the place to start.

While I'm at it, I've never actually seen (nor needed, thus far) Python
code to get an atomic lock on a file.  What's the idiom in Python?

Tim
-- 
If you do not climb, you will not fall. This is true.
But is it that bad to fail, that hard to fall?
    -- Morpheus, The Sandman



More information about the Python-list mailing list