繁体   English   中英

python守护程序线程退出,但进程仍在后台运行

[英]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"

ubuntu机器上ps命令的输出

我仍然看到进程正在运行。 (我现在使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM