【发布时间】:2014-03-12 09:59:31
【问题描述】:
我想知道当父进程试图终止子进程时,是否有办法在子进程上运行一些代码。有没有办法我们可以写一个Exception?
我的代码如下所示:
main_process.py
import Process from multiprocessing
def main():
p1 = Process(target = child, args = (arg1, ))
p1.start()
p1.daemon = True
#blah blah blah code here
sleep(5)
p1.terminate()
def child(arg1):
#blah blah blah
itemToSend = {}
#more blah blah
snmpEngine.transportDispatcher.jobStarted(1) # this job would never finish
try:
snmpEngine.transportDispatcher.runDispatcher()
except:
snmpEngine.transportDispatcher.closeDispatcher()
raise
由于作业永远不会完成,因此子进程会继续运行。我必须从父进程终止它,因为子进程永远不会自行终止。但是,我想在子进程终止之前将itemToSend 发送到父进程。我可以return它以某种方式传递给父进程吗?
更新:让我解释一下pysnmp 模块中的runDispatcher() 是如何工作的
def runDispatcher():
while jobsArePending(): # jobs are always pending because of jobStarted() function
loop()
def jobStarted(jobId):
if jobId in jobs: #This way there's always 1 job remaining
jobs[jobId] = jobs[jobId] + 1
这很令人沮丧。除了做这一切,是否可以自己编写一个 snmp 陷阱侦听器?你能指出我正确的资源吗?
【问题讨论】:
-
@Alp 恐怕两者的答案都是“是”。
snmpEngine.transportDispatcher.runDispatcher()函数无限期运行。它永远不会停止。阻止它的唯一方法是终止整个过程。但我需要子进程将itemToSend发送回父进程,这是在runDispatcher()运行时计算的。 -
@user2511458:在子进程的后台守护线程中运行
runDispatcher,use the main thread to runchild()function as in my answer等待stopped_event,最后发送itemToSend。 -
@J.F. Sebastian 抱歉,我忘了说我的子进程是一个守护进程。并且守护进程不允许有子进程
-
@user2511458: the child process may have multiple threads.
标签: exception python-2.7 return multiprocessing pysnmp