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

2024-10-01 00:35:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是python2.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)

我正在另一个文件中创建一个线程样品.py你说

^{pr2}$

我从命令行得到以下输出:

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

以及样品.py退出。 但当我在终端上使用下面的命令时

ps -ax | grep "adb"

Output of ps command on ubuntu machine

我仍然看到进程在运行。(我现在使用kill-91768117682手动杀死它们)

不知道我在这里缺了什么。在

我的问题是, 1) 为什么我已经在我的程序中终止了这个进程,它还活着?在

2)如果我不去管它会不会造成任何问题?在

3)是否有其他更好的方法使用线程捕获日志并监视日志?在

编辑:按照@bug Killer的建议,我在thread类中添加了下面的方法

def getProcessID(self):
        return os.getpid()

使用os.杀死(c.getProcessID(),SIGTERM)在我的样品.py. 程序根本不退出。在


Tags: thepyself进程initisosdef
1条回答
网友
1楼 · 发布于 2024-10-01 00:35:21

这很可能是因为您正在线程中使用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;重复调用应该很好(很像对file对象的close),因此稍后再调用{}应该不会有任何影响。在

相关问题 更多 >