[CentralOH] SingleInstance Recipe (Windows)

Mark Erbaugh 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)

Thanks.

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:

class SingleInstance:
    """
    Limits application to single instance (Linux / Mac)

    sample usage:

    ==========
    import si_unix
    import sys

    myApp = si_unix.SingleInstance('name')
    if myApp.fail:
        print "Another instance of this program is already running
        sys.exit(0)
    ==========
    
    Make sure myApp is a global and exists as long as the application
    is running.

    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')
        try:
            fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
            self.fail = False
            self.fp = fp
        except IOError:
            self.fail = True
            fp.close()

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/mailman/private/centraloh/attachments/20100803/4b61f4f5/attachment-0001.html>


More information about the CentralOH mailing list