OS independent way to check if a python app is running?

Stephen Hansen apt.shansen at gmail.com
Sun Dec 27 21:25:44 EST 2009


On Sun, Dec 27, 2009 at 4:42 PM, Dan Sommers <somm1105 at bellsouth.net> wrote:

> On Sun, 27 Dec 2009 19:07:12 -0500, python wrote:
>
> > Hans,
> >
> >> Unfortunately, Windows is not a respectable OS. Unlike Unix, it allows
> >> two processes to bind to the same port. The theory is that this somehow
> >> allows the two processes to share their workload. One thing the OP can
> >> portably do, is try to connect() to the port. If that succeeds, then a
> >> server program is already running at that port, so he should exit.
>

In this case, I think doing it in an OS-independant way just complicates
life-- because you just gotta deal with the disrespected :) Some things are
just easier to do the way a particular OS is built, and then let the rest of
the platforms all do it another way.

Here's how we do it at the office:
    if sys.platform == "win32":
        from ctypes import windll
        hMutex = windll.kernel32.CreateMutexA(None, 0, "COMPANY_PROGRAM_%s"
% os.environ['USERNAME'])
        if windll.kernel32.GetLastError() == 183:
            sys.exit()

Where COMPANY and PROGRAM are strings which make the resulting string unique
to this program. The reason I included username is in cases of people
running my app in Terminal Services / Citrix or such where multiple people
are on the machine at once-- my app is a user-app and not a server-app, so
its fine to run multiple times on the one machine, what I really wanted to
prevent was more then one user-per-machine. In your case its probably not
necessarily.

The named mutex will exist in the system indefinitely and any subsequent
attempts to create one of the same name will simply fail; and when your
program closes-- for any reason-- Windows will automatically clean up the
mutex.

Then on any other platform, the socket-binding has been a good solution for
us for this need. I never quite liked the lockfile approach due to some bad
experiences with stale-files, which isn't a problem for sockets and mutexes
as they are automatically cleaned up by the OS (at least eventually) even
after a hard and nasty crash. I don't know if Diez's approach is subject to
that at all, granted-- if its not, awesome :)

Just posting as an FYI in case its interesting in posterity.

--S
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20091227/75471db3/attachment-0001.html>


More information about the Python-list mailing list