Skip to content Skip to sidebar Skip to footer

Call A Function From A Running Process

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 calle

Solution 1:

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

deff(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 itprint 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.

Solution 2:

Parent code:

import signal

defmy_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.

Post a Comment for "Call A Function From A Running Process"