简体   繁体   中英

How to kill subprocess python in windows

How would I go about killing a process on Windows?

I am starting the process with

    self.p = Process(target=self.GameInitialize, args=(testProcess,))
    self.p.start()

I have tried

self.p.kill()
self.p.terminate()
os.kill(self.p.pid, -1)
os.killpg(self.p.pid, signal.SIGTERM)  # Send the signal to all the process groups

Errors

Process Object has no Attribute kill
Process Object has no Attribute terminate
Access Denied

I cannot use .join.

On windows, os.killpg will not work because it sends a signal to the process ID to terminate. This is now how you kill a process on Windows, instead you have to use the win32 API's TerminateProcess to kill a process.

So, you can kill a process by the following on windows:

import signal
os.kill(self.p.pid, signal.CTRL_C_EVENT)

If the above does not work, then try signal.CTRL_BREAK_EVENT instead.

I had to do it using this method from this link :

subprocess.call(['taskkill', '/F', '/T', '/PID',  str(self._active_process.pid)])

This is because self._active_process.kill() was not adequate

You should provide a minimal, working example of the problem you are having. As show below, this minimal, working example correctly terminates the process (Tested on Python 2.7.5 64-bit), so the error you are seeing lies in code you haven't shown.

import multiprocessing as mp
import time

def work():
    while True:
        print('work process')
        time.sleep(.5)

if __name__ == '__main__':
    p = mp.Process(target=work)
    p.start()
    for i in range(3):
        print('main process')
        time.sleep(1)
    p.terminate()
    for i in range(3):
        print('main process')
        time.sleep(.5)

Output:

main process
work process
work process
main process
work process
work process
main process
work process
work process
main process
main process
main process
os.kill(self.p.pid, -9)

Works. I am unsure why -1 returns a access denied error but -9 does not.

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