Python如何杀死根子进程 [英] Python how to kill root subprocess
问题描述
我正在尝试使用root特权启动一个进程,并稍后将其终止.
I'm trying to launch a process with root privileges and kill it later on.
但是由于某种原因,我无法使其正常工作.
But for some reason, I can't get it to work.
这是一个小脚本,可以重现我的问题(免责声明:代码有点脏,仅用于错误重现):
Here is a small script to reproduce my problem (disclaimer: code is a bit dirty its only for bug reproduction):
import os
import time
import subprocess
command = ["sudo", "sleep", "25"]
process = subprocess.Popen(command,
bufsize=1,
stdin=open(os.devnull),
stderr=subprocess.PIPE,
stdout=subprocess.PIPE)
def kill():
pid = process.pid
cmd = "sudo kill %s" % pid
print(cmd)
print(os.system(cmd))
time.sleep(2)
kill()
stdout, stderr = process.communicate()
print("stdout: " + stdout)
print("stderr: " + stderr)
ret = process.wait()
print("ret: " + str(ret))
此代码似乎无法杀死我的子进程,但是当我在另一个python实例中启动os.system("sudo kill <pid>")
时,它确实起作用.
This code doesn't seem to be able to kill my subprocess, but when I launch os.system("sudo kill <pid>")
in another python instance, it does work.
推荐答案
您也可以尝试使用此方法.在这里,我试图为会话组设置一个会话ID,该进程组可能在子进程调用期间创建,并且当您想要终止时,将信号发送给进程组负责人,并将其传输到该进程的所有子进程中.组.
You may try this one too. Here what I tried to do is setting a session id to the group of processes that may get created during the subprocess call and when you want kill, a signal is sent to the process group leader, it's transmitted to all of the child processes of this group.
import signal
process = subprocess.Popen(command,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
preexec_fn=os.setsid) # add session id to group
print(process.pid)
def kill():
pid = process.pid
cmd = "sudo kill %s" % pid
print(cmd)
os.killpg(os.getpgid(process.pid), signal.SIGTERM) # send signal to the group
time.sleep(2)
kill()
这篇关于Python如何杀死根子进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!