Sometimes it is necessary to ensure that only one instance of application is running. This quite simple solution uses pid file to achieve this, and will run only on Linux platform. This is a nearly compatible version to the Windows version posted by Dragan Jovelic (I fixed the mispelling of alreadyrunning method).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | import commands
import os
class singleinstance(object):
'''
singleinstance - based on Windows version by Dragan Jovelic this is a Linux
version that accomplishes the same task: make sure that
only a single instance of an application is running.
'''
def __init__(self, pidPath):
'''
pidPath - full path/filename where pid for running application is to be
stored. Often this is ./var/<pgmname>.pid
'''
self.pidPath=pidPath
#
# See if pidFile exists
#
if os.path.exists(pidPath):
#
# Make sure it is not a "stale" pidFile
#
pid=open(pidPath, 'r').read().strip()
#
# Check list of running pids, if not running it is stale so
# overwrite
#
pidRunning=commands.getoutput('ls /proc | grep %s' % pid)
if pidRunning:
self.lasterror=True
else:
self.lasterror=False
else:
self.lasterror=False
if not self.lasterror:
#
# Write my pid into pidFile to keep multiple copies of program from
# running.
#
fp=open(pidPath, 'w')
fp.write(str(os.getpid()))
fp.close()
def alreadyrunning(self):
return self.lasterror
def __del__(self):
if not self.lasterror:
os.unlink(self.pidPath)
if __name__ == "__main__":
#
# do this at beginnig of your application
#
myapp = singleinstance()
#
# check is another instance of same program running
#
if myapp.alreadyrunning():
sys.exit("Another instance of this program is already running")
#
# not running, safe to continue...
#
print "No another instance is running, can continue here"
|
Tags: threads
Checking if a pid is running can be done using
This is more portable than the current implementation.
I've got a basic framework here which uses a simple asynchronous client/server so that subsequent invocations do not start a new instance and also pass their command line parameters to the first one.
Miki Tebeka's method for testing the pid is more robust. The 'ls | grep' method will give false result for example if testing pid=4412 and some other process has pid=144112. Also, I had to modify one line...
os.kill( int(pid), 0)
Otherwise works great (on RHEL4 Python2.2)