How do I force a single instance of a python app?
Aquarius
aquarius at kryogenix.org
Tue Oct 24 19:03:05 EDT 2000
Joshua Muskovitz spoo'd forth:
> I need to prevent multiple copies of a python app from running
> simultaneously on a single machine. In Windows and C++, this is done with
> sending custom window messages to all top level windows, or using some other
> kind of scheme.
>
> I'm looking for a platform neutral way to do this for my python apps -- the
> second instance should somehow detect the first instance and should quietly
> kill itself. It does not need to notify the first instance of anything.
> Initial target platforms are Solaris and NT, but others will follow, so a
> generic solution would be the best. File existence is a bad solution
> because the first instance might (possibly) terminate before it could delete
> the file. I need a semaphore which will absolutely go away when the first
> instance dies, or else a way to reliably probe to see if the first instance
> exists on the fly.
It could open a socket on a specific port and listen for a connection, or
watch for UDP packets, and an instance, when starting, pokes the socket
to see if it gets a "yes, I'm already running, kill yourself" response.
Couple of flaws with this idea: (a) it's a lot of overhead :) (b) if
something else is already running on that socket, then (i) your app will
not be able to bind a listener to it, and (ii) the other app might throw
a bit of a wobbly if you send it a random "I am here" message, depending
on what it is :)
You *could* sort of hack a file-existence thing that makes the first
instance write the current time to the file every minute or so; if an
instance fires and finds the flag file, but the time in it is more than a
minute old, then you know that an instance ran but died before it could
delete the file, and you're safe to start. This does mean that you're
unable to start a second instance within a minute of the first instance
dying incorrectly, which might cause a problem.
You could also have the first instance create two files which are
actually named pipes, so a second instance can communicate with the first
instance (and if the first instance dies incorrectly there'll be no
response from the pipes), but I don't know if every OS supports named
pipes.
loads-of-inefficient-solutions-ly-y'rs,
Aq.
--
An Oxford scholar, meeting a porter, who was carrying a hare through the
streets, accosts him with this extraordinary question: "Prithee, friend,
is that thy own hare, or a wig?"
"Popular Fallacies: That The Worst Puns Are The Best" -- Essays of Elia
More information about the Python-list
mailing list