简体   繁体   中英

Python: timed-out psutil process killed (as instructed) in Windows, but not in Linux

This works as I expect it to on Windows (64-bit Windows 7 Home Premium, SP1), using Python 3.5.1. However, on Linux (OpenSUSE 13.2, Harlequin, i586 with KDE 4.14.9), using Python 3.4.1, any timed-out process never gets killed.

My process handling is basically that of the answer given on StackOverflow to Python: Run a process and kill it if it doesn't end within one hour (by Giampaolo Rodolà, on May 10 2012)

Here's (simplified) what I did:

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()

Rather than the FoxitReader process being killed after 5 seconds, the PDF file continued to stay open in FoxitReader.

The resulting Python interpreter output was:

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

Sometimes, the output also included a lot more, seemingly from Qt (which I think the Linux version of FoxitReader is written with). I don't think it's relevant, but (in case I'm wrong) here 's an example.

I tried doing:

process.terminate()

before the:

process.kill()

(as it looked like How to kill Linux process with Python might be suggesting, but that made no difference.

[This is for some Python3 'fuzz testing' of PDF readers. I randomly change some bytes in valid PDF files, and then test to see if any of the 'fuzzed' files crash any of the PDF readers. It occasionally does cause 1 of them to crash.]

Oops! I hadn't realized.

Unlike on Windows, on Linux (or at least on OpenSUSE 13.2, Harlequin, i586 with KDE 4.14.9, using Python 3.4.1), FoxitReader gets run in a child process, so that also needs to be killed.

I was able to do that as instructed in jung rhew's Nov. 20, 2014 answer to StackOverflow question how to kill process and child processes from python?

Probably you should specify the kill code. According to the docs, the kill() method takes arguments. Try with p.kill(pid=your_pid_num, 9), because it says 'on UNIX this is the same as os.kill(pid, signal.SIGKILL).' https://pythonhosted.org/psutil/#psutil.Process.kill

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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