[英]How to restart a process using python multiprocessing module
我正在嘗試使用多處理模塊重新啟動 python 進程,但出現“斷言錯誤:無法啟動進程兩次”。
我的問題
import time
from multiprocessing import Process
def worker ():
while True:
print "Inside the worker"
time.sleep(10)
p1 = Process(target=worker,name="worker")
p1.start()
#p1.join()
time.sleep(3)
p1.terminate()
print "after Termination "
time.sleep(3)
p1.start()
實際上,我正在嘗試創建一個進程監視器功能來監視所有進程的內存和 CPU 使用情況。 如果達到一定水平,我想實時重新啟動
我希望它會幫助你
import time
from multiprocessing import Process
def worker ():
while True:
print "Inside the worker"
time.sleep(10)
def proc_start():
p_to_start = Process(target=worker,name="worker")
p_to_start.start()
return p_to_start
def proc_stop(p_to_stop):
p_to_stop.terminate()
print "after Termination "
p = proc_start()
time.sleep(3)
proc_stop(p)
time.sleep(3)
p = proc_start()
print "start gain"
time.sleep(3)
proc_stop(p)
我怎樣才能重新開始這個過程?
您無法重新啟動已終止的進程。 您需要實例化一個新進程。
一旦它終止為什么它會變成僵屍模式?
因為在 Unix-y 系統上,父進程需要在內核清除進程表中的相應條目之前讀取退出代碼。
如何刪除僵屍進程?
您有多種選擇。 我在這里引用文檔:
加入僵屍進程
在 Unix 上,當一個進程完成但尚未加入時,它會變成僵屍。 永遠不應該有很多,因為每次新進程啟動(或調用 active_children() )時,所有尚未加入的已完成進程都將被加入。 同時調用已完成進程的 Process.is_alive 將加入該進程。 即便如此,明確加入您啟動的所有流程可能是一種很好的做法。
實際上,我正在嘗試創建一個進程監視器功能來監視所有進程的內存和 CPU 使用情況。
為此,您應該查看psutil模塊。
如果你只是想暫停(不是kill)的過程,如果內存消耗得高,你也許可以從我的回答得出一些啟示這里。
terminate() 進程將不允許重新啟動該進程,但可以使用 kill() 進程並且可以重新啟動該進程。 有用
import time
from multiprocessing import Process
def worker ():
while True:
print "Inside the worker"
time.sleep(10)
p1 = Process(target=worker,name="worker")
p1.start()
#p1.join()
time.sleep(3)
p1.kill()
print "after kill"
time.sleep(3)
p1.start()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.