我有以下代码
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打印出signum,但循环继续。我甚至尝试在循环中打印self.kill_received值。即使在执行信号处理程序之后,它也显示为false。
另外,如果我在信号处理程序中放置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)时,只会发生信号处理程序中的打印。变量未设置。