How to stop multiple processes from creating multiple instances of another process?
Question: I have 2 processes: Start and Status. There can be multiple Start processes
executed on the same time and there should only be 1 instance of Status
process.

On startup of the Start process, it will attempt to start Status. At the
moment, I try to stop multiple Statuses from starting by getting the Status
process to check if Status's server port has been binded to determine if there
is another Status that exists and if so it will shutdown gracefully.

However this has a race condition where the time it checks for the binded
port, there might be another Status that had done that check and is in the
process of binding that port, hence 2 Statuses will be created.

Is there a process level solution to this? I have considered having another
process monitoring the number of Statuses in the System but is there another
approach?

Edit: This is done in Python 2.6

Edit2: Both Start and Status are excuted from the shell.


Answer: First, you can use something like [supervisord](http://supervisord.org/) to
coordinate running of processes. It's actually quite good. You basically
configure your processes, the max number that can run, etc and it will handle
the rest. You need to figure out all the little configuration items, though.
You might also want to break out that status process to be its own if you have
it running as a thread in another process. You'll have better success that
way.

You can make this less of an issue probably if you changed how you handled
this. Instead of a check then execute, just execute and handle the error.

    
    
    try: 
        open_port_listener()
    except socket.error as e:
        do_nothing()
    

Or maybe put in a little more granular check on the type of socket error. I am
assuming you are using `socket` and are getting a socket.error (probably
Address already in use or something?).

If you were running this using the `multiprocessing` module (which I know you
aren't since you clarified, but I'll leave this in just in case it is useful
for anyone else), you could use a lock to ensure the status process check
occurs on one process or another. The `multiprocessing` module supports this.
Read the docs
[here](https://docs.python.org/2/library/multiprocessing.html#synchronization-
between-processes).

    
    
    from multiprocessing import Process, Lock
    
    def startStatusProcess(l):
        l.acquire()    
        if not do_check():
            Process(target=runStatusProcess, args=()).start()
        l.release() 
    
    if __name__ == '__main__':
        lock = Lock()
        startStatusProcess(lock)
    

