[Tutor] how to know if process is running?

Chris Fuller cfuller084 at thinkingplanet.net
Tue Jul 28 18:51:39 CEST 2009


On Tuesday 28 July 2009 10:45, shawn bright wrote:
> Hey all,
>
> I have an app that runs in a GUI written in pygtk. It spawns several
> threads, and runs all the time.
> It is mission critical that we can never have two instances of this
> running at once.
>
> So, my question is, how can i write something that will know if there
> is an instance of that something already running?
>
> I am doing this in python 2.5 on Ubuntu, if that matters ( which i
> suspect it does ).

The usual way is with file locks, but these are tricky to do in a cross 
platform way, and I find that when the program crashes unexpectedly, it can 
take awhile for the locks to get cleaned up by the operating system.

What I do is open an UDP socket.  The code is dead simple:

from socket import socket, AF_INET, SOCK_DGRAM

def check_port(addr):
   s = socket(AF_INET, SOCK_DGRAM)

   try:
      s.bind( addr )
   except SocketError, e:
      if type(e.args) == tuple:
         if e[0] == errno.EADDRINUSE:
            return True

      raise

   else:
      s.close()
      return False

def check_port(addr):
   return check_port(addr, SOCK_DGRAM)

# returns False if the port is bound
def socket_lock(port, check_only=False):
   s = socket(AF_INET, SOCK_DGRAM)
   addr = ('localhost', port)

   if not check_port(addr):
      if not check_only:
         s.bind( addr )
         return s
      else:
         return True
   else:
      return False


addr is the address tuple used by the socket module.  First element is 
hostname (usually "localhost"), and the second element is the port number.  
Note that you need root/Administrator privileges to open a port under 1024.

Cheers


More information about the Tutor mailing list