Hi,
my programm starts a subprocess, which has to send some kind of signal to the parent after initialization. It would be perfekt if i could set up a handler in parent, which is called when this signal is sent. Is there any way to do it?
Alendit
Hi,
my programm starts a subprocess, which has to send some kind of signal to the parent after initialization. It would be perfekt if i could set up a handler in parent, which is called when this signal is sent. Is there any way to do it?
Alendit
You can use the signal module from the Python standard library to register a signal handler. The subprocess would then use normal signal sending mechanisms.
Parent code:
import signal
def my_callback(signal, frame):
print "Signal %d received" % (signal,)
signal.signal(signal.SIGUSR1, my_callback)
# start child
Child code:
import os
import signal
signal.kill(os.getppid(), signal.SIGUSR1)
Be careful with this form of IPC because it has its issues, e.g.:
In the original Unix systems, when a handler that was established using signal() was invoked by the delivery of a signal, the disposition of the signal would be reset to SIG_DFL, and the system did not block delivery of further instances of the signal. System V also provides these semantics for signal(). This was bad because the signal might be delivered again before the handler had a chance to reestablish itself. Furthermore, rapid deliveries of the same signal could result in recursive invocations of the handler.
I recommend reading the whole signal(2) man page.
If you are using Python 2.6, you can use the multiprocessing
module from the standard library, in particular pipes and queues. Simple example from the docs:
from multiprocessing import Process, Pipe
def f(conn): #This code will be spawned as a new child process
conn.send([42, None, 'hello']) #The child process sends a msg to the pipe
conn.close()
if __name__ == '__main__':
parent_conn, child_conn = Pipe()
p = Process(target=f, args=(child_conn,)) # prepare to spawn the child
p.start() # spawn it
print parent_conn.recv() # prints "[42, None, 'hello']"
p.join() #wait for child to exit
If you are using Python 2.4 or 2.5, don't despair - a backport is available here.