Python:超时的psutil进程在Windows中被杀死(如指示),但在Linux中没有

时间:2016-02-01 19:05:25

标签: python process psutil

这可以像我期望的那样在Windows(64位Windows 7家庭高级版,SP1)上使用Python 3.5.1。 但是,在Linux(OpenSUSE 13.2,Harlequin,带有KDE 4.14.9的i586)上,使用Python 3.4.1,任何超时进程都不会被杀死。

我的进程处理基本上是StackOverflow给出的答案 到Python: Run a process and kill it if it doesn't end within one hour (作者:GiampaoloRodolà,2012年5月10日)

这是(简化)我所做的:

import os
import psutil


if os.name == 'nt':  # If running on Windows...
    app = r'C:\Program Files (x86)\Foxit Software\Foxit Reader\FoxitReader.exe'
else:
    app = r'apps/foxitreader/FoxitReader.sh'

process = psutil.Popen([app, os.path.join('raw_pdfs', 'Thinkpython.pdf')])

try:

    process.wait(timeout=5.0)  # Wait specified seconds to see if application crashes.

    print('Process crashed with return code %d.' % process.poll())
    # If you get here, the process crashed before timing out.

except psutil.TimeoutExpired:  # If the timeout expired as normally expected, Then...

    print('Process timed-out normally.')

    process.kill()

而不是在5秒后杀死FoxitReader进程,PDF文件继续在FoxitReader中保持打开状态。

生成的Python解释器输出为:

Openfile()---fileName-: "raw_pdfs/Thinkpython.pdf"
sendMessage
Process timed-out normally.

有时,输出还包括更多,似乎来自Qt(我认为FoxitReader的Linux版本是用的)。 我不认为这是相关的,但(如果我错了)here就是一个例子。

我尝试过:

process.terminate()

之前:

process.kill()

(看起来像How to kill Linux process with Python可能暗示的那样,但这没有任何区别。

[这是针对PDF阅读器的一些Python3'模糊测试'。  我随机更改了有效PDF文件中的一些字节,然后测试是否有任何“模糊”文件导致任何PDF阅读器崩溃。  它偶尔会导致其中一个崩溃。]

2 个答案:

答案 0 :(得分:1)

糟糕!我没有意识到。

与Windows不同,在Linux上(或者至少在OpenSUSE 13.2,Harlequin,带有KDE 4.14.9的i586,使用Python 3.4.1),FoxitReader会在子进程中运行,因此也需要被杀死。 / p>

我能按照jung rhew的指示做到这一点,2014年11月20日回答StackOverflow问题how to kill process and child processes from python?

答案 1 :(得分:0)

可能你应该指定kill代码。根据文档,kill()方法接受参数。尝试使用p.kill(pid = your_pid_num,9),因为它在UNIX上表示这与os.kill(pid,signal.SIGKILL)相同。' https://pythonhosted.org/psutil/#psutil.Process.kill

相关问题