2

In python, is there a cross platform way of creating something similar to Windows named Event in one process, and set it from another process to signal something to the first one?

My specific problem is that I need to create a process that on startup will check if any other instances of itself are running, and if so, signal them to quit. With Windows API I would use CreateEvent with the lpName parameter, and SetEvent.

Tzach
  • 12,889
  • 11
  • 68
  • 115

2 Answers2

2

I've spent about a day now searching for a good answer to this and here is what I am coming up with at this moment:

It is possible to use signals to indicate to the process that some change needs to take place, however in a more complex legacy codebase I am dealing with it causes the process to crash. Signaling interrupts various I/O processes and alike based on python signal docs. You can implement signal handler with signal.SIGUSR1

import signal

def signal_handler(signum, stack):
  print('Signal %d received'%signum)

signal.signal(signal.SIGUSR1, signal_handler)

This code can be triggered in Linux et al. through:

$ kill -s SIGUSR1 $pid 

I am presently leaning towards kazoo Python Zookeeper library. It requires to stand up Zookeeper as infrastructure.

I do have an additional need for toggling configuration values in my case. However Zookeeper supports a number of interprocessor communication tools that will serve your needs.

UPDATE: I finally settled on a named pipe (FIFO), calling it inside a thread with readline.

    if not os.path.exists(fifo_name):
        os.mkfifo(fifo_name)
    while True:
        with open(fifo_name, 'r') as config_fifo:
            line = config_fifo.readline()[:-1]
            print(line)

I used tempfile.gettempdir() to find a good location to place the FIFO in the file system. It requires quite a bit of refinement however, since I did not care to parse passed content while you might. Also if you are planing on having more then one consumer of the event you are going to have it propagated to only one consumer as it is a queue.

0

It seems to me that this is not so much a question as to whether this is possible in Python, but whether such a cross-platform approach exists: if one does, then even if no directly written Python exists, one can always make system calls using subprocess.call() and the like.

As for whether it's a possibility, I can't profess to be much of an expert, but a bit of a search has thrown up these discussions which might prove helpful to you.

Community
  • 1
  • 1
unwitting
  • 3,346
  • 2
  • 19
  • 20
  • 1
    Thanks, but it doesn't really matter to me if the answer will give exact behavior as Windows Events. I only need to be able to signal something to another process which is not a child process (and without tricks like using files, etc.). I guess other OS have features for this. – Tzach Jan 20 '14 at 12:11