[英]python daemon thread exits but process still run in the background
我正在使用python 2.7,並且在主程序退出后Python線程不會終止其進程。 (在ubuntu機器上使用ps -ax命令進行檢查)
我有下面的線程類,
import os
import threading
class captureLogs(threading.Thread):
'''
initialize the constructor
'''
def __init__(self, deviceIp, fileTag):
threading.Thread.__init__(self)
super(captureLogs, self).__init__()
self._stop = threading.Event()
self.deviceIp = deviceIp
self.fileTag = fileTag
def stop(self):
self._stop.set()
def stopped(self):
return self._stop.isSet()
'''
define the run method
'''
def run(self):
'''
Make the thread capture logs
'''
cmdTorun = "adb logcat > " + self.deviceIp +'_'+self.fileTag+'.log'
os.system(cmdTorun)
我正在另一個文件sample.py中創建一個線程,
import logCapture
import os
import time
c = logCapture.captureLogs('100.21.143.168','somefile')
c.setDaemon(True)
c.start()
print "Started the log capture. now sleeping. is this a dameon?", c.isDaemon()
time.sleep(5)
print "Sleep tiime is over"
c.stop()
print "Calling stop was successful:", c.stopped()
print "Thread is now completed and main program exiting"
我從命令行獲得以下輸出:
Started the log capture. now sleeping. is this a dameon? True
Sleep tiime is over
Calling stop was successful: True
Thread is now completed and main program exiting
然后sample.py退出。 但是當我在終端上使用下面的命令時,
ps -ax | grep "adb"
我仍然看到進程正在運行。 (我現在使用kill -9 17681 17682手動殺死它們)
不知道我在這里想念的是什么。
我的問題是:1)為什么我在程序中將其殺死后,該過程仍然存在?
2)如果我不理會它會產生任何問題嗎?
3)還有其他更好的方法來使用線程捕獲日志並監視日志嗎?
編輯:正如@bug Killer所建議,我在線程類中添加了以下方法,
def getProcessID(self):
return os.getpid()
並在我的sample.py中使用了os.kill(c.getProcessID(),SIGTERM) 。 該程序根本不會退出。
可能是因為您在線程中使用os.system
。 即使殺死線程,從os.system
派生的進程os.system
將保持活動狀態。 實際上,除非您在代碼中或用手工方式明確終止它(這聽起來像您最終正在做的事情)或所生成的進程自行退出,否則它將一直存在。 您可以改為:
import atexit
import subprocess
deviceIp = '100.21.143.168'
fileTag = 'somefile'
# this is spawned in the background, so no threading code is needed
cmdTorun = "adb logcat > " + deviceIp +'_'+fileTag+'.log'
proc = subprocess.Popen(cmdTorun, shell=True)
# or register proc.kill if you feel like living on the edge
atexit.register(proc.terminate)
# Here is where all the other awesome code goes
由於您所要做的只是產生一個進程,因此創建一個線程來執行它是過大的,只會使您的程序邏輯復雜化。 只需如上所述在后台生成該進程,然后在程序退出時讓atexit
終止它即可。 和/或顯式調用proc.terminate
; 重復調用(就像close
文件對象一樣)應該沒問題,因此稍后再次使用atexit
調用不會有任何傷害。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.