Call a function from a running process

て烟熏妆下的殇ゞ 提交于 2019-12-13 06:31:36

问题


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


回答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

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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/1393242/call-a-function-from-a-running-process

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!