How can I avoid running a python script multiple times?
jepler at unpythonic.net
Tue Jan 28 15:15:01 CET 2003
While not a complete solution to your problem, you can use os.kill(pid, 0)
to find out if a process exists. On my system, there can be three
os.kill(pid, 0) -> None: process exists, and you are process owner
os.kill(pid, 0) -> OSError, Operation not permitted:
process exists, you are not owner or root
os.kill(pid, 0) -> OSError, No such process:
process does not exist
beware that if your program died long ago but left it's pidfile there's
no guarantee that another process has been given the same pid. In fact,
a malicious user could find out the pid, then wait for it to die for
some reason, and quickly fork() enough times to get a process with that
pid. Then you will believe that your program is still running, even
though it has stopped.
Nevertheless, this is the model used by many "one instance" unix
Other approaches include:
* Have init spawn the process from inittab. init will re-spawn the
process when it dies, but will never start two concurrent programs
from the same inittab line
* If the process uses some resource that requires exclusive access
by its nature (for instance, bind()ing a well-known port number)
then a second instance will fail to run anyhow
* Unix pipes and X properties offer two more ways to determine if a
program is running, and may additionally let you transmit commands
to the existing instance of the program if it is invoked again. The
links text-mode browser uses unix pipes for this purpose, and Mozilla
uses (I believe) X properties.
I tried but failed to work out how to let only one opener of a unix
pipe succeed. The X property approach may be prone to race
conditions, I don't know enough about that to say.
More information about the Python-list