无法终止 Popen 进程

问题描述 投票:0回答:1

我有一个具有以下结构和必要导入的 Python 程序:

def startLogger(logger_dir):
    command0 = 'adb logcat -c'
    command1 = 'adb logcat'
    command2 = 'python3 '+logger_dir+'main.py'

    clear_logcat = subprocess.run(command0.split())
    logcatHandle = subprocess.Popen(command1.split(),stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False)
    loggerHandle = subprocess.Popen(command2.split(),stdin=logcatHandle.stdout,shell=False)
    return logcatHandle, loggerHandle

def closeLogger(logcatInstance, loggerInstance):
    loggerInstance.kill() #Killing it first so that it doesn't break the input PIPE
    logcatInstance.kill()
    return logcatInstance, loggerInstance

def main():
    logger_dir = '/Users/Desktop/logger/'
    print("Starting Logger")
    logcatHandle, loggerHandle = startLogger(logger_dir)
    time.sleep(10)
    logcat, logger = closeLogger(logcatHandle, loggerHandle)

main()

代码运行良好,我可以在 Android 设备上执行 logcat,提取日志,并将其提供给我的记录器,从而在记录器文件创建的文本文件中提供所需的输出。但是,我无法杀死这两个进程。我尝试过

terminate()
方法、
os.kill(process.pid, signam.SIGKILL)
preexec_fn
标志、
os.killpg()
等方法,但记录器仍然在后台运行。这里可能出现什么问题?

python unix subprocess popen kill
1个回答
0
投票

您应该确保在终止进程之前正确关闭管道。

另外,不要使用“kill”,而是使用“terminate”来给进程一个清理的机会。如果没有,则使用“kill”。

然后,确保子进程不会继承不必要的文件描述符,这可能会使它们保持运行。

考虑这些变化,尝试使用

import subprocess
import time
import os
import signal

def startLogger(logger_dir):
    command0 = 'adb logcat -c'
    command1 = 'adb logcat'
    command2 = 'python3 ' + logger_dir + 'main.py'

    
    clear_logcat = subprocess.run(command0.split())
    logcatHandle = subprocess.Popen(command1.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE, preexec_fn=os.setsid)
    loggerHandle = subprocess.Popen(command2.split(), stdin=logcatHandle.stdout, preexec_fn=os.setsid) #this starts each subrprocess in a new session
    return logcatHandle, loggerHandle

def closeLogger(logcatInstance, loggerInstance):
    loggerInstance.terminate()
    try:
        loggerInstance.wait(timeout=5)
    except subprocess.TimeoutExpired:
        loggerInstance.kill()

    logcatInstance.terminate()
    try:
        logcatInstance.wait(timeout=5)
    except subprocess.TimeoutExpired:
        logcatInstance.kill()
    
    os.killpg(os.getpgid(logcatInstance.pid), signal.SIGTERM)
    os.killpg(os.getpgid(loggerInstance.pid), signal.SIGTERM)
    
    return logcatInstance, loggerInstance

def main():
    logger_dir = '/Users/Desktop/logger/'
    print("Starting Logger")
    logcatHandle, loggerHandle = startLogger(logger_dir)
    time.sleep(10)
    logcat, logger = closeLogger(logcatHandle, loggerHandle)
    print("Logger stopped")

if __name__ == "__main__":
    main()

希望有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.