我有以下代码
def signal_handler(self,signum,frame):
self.kill_received = True
print "signal received",signum
self.condition.set()
def mainFunc(self):
while not self.kill_received:
* do something *
已经观察到,当实际信号出现时,signal_handler 打印符号,但循环继续。我什至尝试在循环内打印 self.kill_received 值。即使在信号处理程序执行之后,它也显示为假。
此外,如果我在信号处理程序中打印 self.kill_received,我可以看到它已变为 True。但它并没有反映在外面。即使我从信号处理程序调用一个函数,它也反映了 kill_received 的修改值。就好像主进程和信号处理程序有两个并行地址空间或其他东西(不确定,因为我是 Python 新手,它的内部工作原理未知)
有人可以解释 Python 中实例变量的这种行为吗?我尝试使用'global kill_received',但它给出了“未定义”错误..
这是应要求提供的完整代码
class CreateData(multiprocessing.Process):
def __init__(self, recv_queue, reportName, reportDirectory, condition, chunkSize = 100, maxReportSize = 350, isChunked = True):
multiprocessing.Process.__init__(self)
self.reportName = reportName
self.reportDirectory = reportDirectory
self.recv_queue = recv_queue
self.chunkSize = chunkSize * 1024 * 1024
self.maxReportSize = maxReportSize * 1024 * 1024
self.current_chunk_size = 0
self.isChunked = isChunked
self.chunk_suffix = 0
# Flow control attributes
signal.signal(signal.SIGTERM,self.signal_handler)
signal.signal(signal.SIGUSR1,self.signal_handler)
self.kill_received = False
self.condition = condition
def signal_handler(self,signum,frame):
self.kill_received = True
print "signal received",signum
self.condition.set()
def run(self):
self.makeReport(True)
def makeReport(self,isChunked):
swing=20*(self.chunkSize/100)
up_swing=(self.chunkSize+swing) #upper swing size
low_swing=(self.chunkSize-swing) #lower swing size
while(not self.kill_received):
#{
self.funcTest()
#}
编辑 仅当从此类中的函数启动信号时才会出现此问题。如果我从主进程执行 os.kill(child_pid,signal) ,它将按预期处理。
但是当我从此类中的函数执行 os.kill(os.ppid(),signal) 时,只会发生信号处理程序中的打印。未设置变量。