[CentralOH] SingleInstance Recipe (Windows)
mark at microenh.com
Wed Aug 4 03:34:31 CEST 2010
On Aug 3, 2010, at 9:04 PM, m g wrote:
> For a simple solution on a UNIX box, I would write the process id to,
> or at least touch, /var/run/myapp.pid. If the pid file already
> exists, I know that the application is already running. Of course,
> the possibility exists that something happened to the application, and
> it was not able to remove the pid file.... just delete the pid file if
> you are sure its not running: ps ax | grep $(cat /var/run/myapp.pid)
I found a couple of solutions for Unix. One was similar to what you suggest. In fact, I found a recipe at ActiveState that if if found a .pid file tested to see if the process was running.
The other users fcntl.flock to lock this file and fail if a lock couldn't be obtained. Here's some code I modeled after that:
Limits application to single instance (Linux / Mac)
myApp = si_unix.SingleInstance('name')
print "Another instance of this program is already running
Make sure myApp is a global and exists as long as the application
The key is that myApp hangs on to a copy of the file handle (self.fp)
only if the call to CreateMutex is successful.
When myApp goes out of scope, self.fp is released and another
instance of the application can run.
def __init__(self, name):
pid_file = os.path.join(os.path.sep, 'var', 'run', '%s.pid' % name)
fp = open(pid_file, 'w')
fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
self.fail = False
self.fp = fp
self.fail = True
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the CentralOH