2013-01-20 23 views
2

當你執行一個python腳本時,進程/解釋器退出是因爲它從腳本中讀取了一個EOF字符? [即是退出信號]python進程如何知道何時退出?

的跟進這是怎麼了/當一個Python子進程知道要退出,即當您通過重寫run()方法啓動子進程,如下:?

class Example(multiprocessing.Process): 
    def __init__(self, task_queue, result_queue): 
     multiprocessing.Process.__init__(self) 
     self.task_queue = task_queue 
     self.result_queue = result_queue 

    def run(self): 
     while True: 
      next_task = self.task_queue.get() 
      if next_task is None: 
       print '%s: Exiting' % proc_name 
       break 
#more stuff...[assume there's some task_done stuff, etc] 

if __name__ == '__main__': 
    tasks = multiprocessing.JoinableQueue() 
    results = multiprocessing.Queue() 

    processes = [ Example(tasks, results) 
        for i in range(5) ] 
    for i in processes: 
     i.start() 
#more stuff...like populating the queue, etc. 

現在,我很好奇的是:子進程在run()方法完成後自動退出嗎?如果我在執行過程中殺死主線程,子進程會立即結束嗎?如果它們的run()調用可以獨立於父進程的狀態完成,它們會結束嗎?

回答

1

是的,每個子進程在完成run方法後自動終止,即使我認爲您應該避免繼承Process並使用target參數。

注意,在Linux中,子進程可能繼續留在殭屍狀態,如果你不讀退出狀態:

>>> from multiprocessing import Process 
>>> def target(): 
...  print("Something") 
... 
>>> Process(target=target).start() 
>>> Something 

>>> 

如果我們看一下過程在此之後:

enter image description here

而如果我們讀取過程的退出狀態(使用Process.exitcode),則不會發生。

每個Process實例在後臺啓動一個新進程,該子進程終止的方式和時間取決於操作系統。每個操作系統提供了進程之間的一些平均通信。子進程通常是而不是如果終止「父」進程,則會終止。

例如這樣:

>>> from multiprocessing import Process 
>>> import time 
>>> def target(): 
...  while True: 
...    time.sleep(0.5) 
... 
>>> L = [Process(target=target) for i in range(10)] 
>>> for p in L: p.start() 
... 

主要Python進程將有10個孩子:

enter image description here

現在,如果我們殺了那個過程中,我們得到這樣的:

enter image description here 注意孩子如何處理由init和ar繼承的地方e仍在運行。

但是,正如我所說,這是特定於操作系統。在某些操作系統上殺死父進程會殺死所有子進程。

相關問題