检查进程是否仍在运行
I have the following problem:
我有以下问题:
I need my Python script run a bash script. In case the bash script is running more than let's say 10 seconds, I need to kill it. This is what I have so far:
我需要我的Python脚本运行一个bash脚本。如果bash脚本运行超过10秒,我需要杀死它。这是我到目前为止:
cmd = ["bash", "script.sh", self.get_script_path()]
process = subprocess.Popen(cmd)
time.sleep(10) # process running here...
procinfo = psutil.Process(process.pid)
children = procinfo.children(recursive=True)
for child in children:
os.kill(child.pid, signal.SIGKILL)
The thing I am afraid of is this scenario: The bash script finishes in 1 second, frees its PID and the system passes the PID to another process. After 10 seconds, I kill the PID which I think it belongs to my script but it is not true and I kill some other process. The script needs to be run as root because I require chroot
in it.
我担心的是这种情况:bash脚本在1秒内完成,释放其PID并且系统将PID传递给另一个进程。 10秒后,我杀死了PID,我认为它属于我的脚本,但事实并非如此,我杀死了其他一些进程。该脚本需要以root身份运行,因为我需要chroot。
Any ideas?
3 个解决方案
#1
2
Since you are already using psutil
I suggest you replace the calls to the subprocess
module with calls to psutil.Popen
. This class has the same interface of subprocess.Popen
but provides all the functionality of psutil.Process
.
由于您已经在使用psutil,我建议您通过调用psutil.Popen来替换对子进程模块的调用。此类具有与subprocess.Popen相同的接口,但提供了psutil.Process的所有功能。
Also note that the psutil
library pre-emptively checks for PID reuse already, at least for a number of methods including terminate
and kill
(just read the documentation for Process
).
另请注意,psutil库已经先发制人地检查PID重用,至少对于包括终止和终止在内的多种方法(只需阅读Process的文档)。
This means that the following code:
这意味着以下代码:
cmd = ["bash", "script.sh", self.get_script_path()]
process = psutil.Popen(cmd)
time.sleep(10) # process running here...
children = process.children(recursive=True)
for child in children:
child.terminate() # try to close the process "gently" first
child.kill()
Note that the documentation for children
says:
请注意,儿童文档说:
children(recursive=False)
Return the children of this process as a list of
Process
objects, preemptively checking whether PID has been reused.将此进程的子进程作为Process对象列表返回,抢先检查PID是否已被重用。
In summary this means that:
总之,这意味着:
- When you call
children
thepsutil
library checks that you want the children of the correct process and not one that happen to have the same pid - When you call
terminate
orkill
the library makes sure that you are killing your child process and not a random process with the same pid.
当你调用孩子时,psutil库会检查你是否想要正确进程的子进程,而不是那些碰巧拥有相同pid的进程
当您调用终止或终止库时,请确保您正在查杀子进程,而不是使用相同pid的随机进程。
更多相关文章
- 解决僵尸进程
- Linux(Debian)设置开机自启动脚本
- Linux网络和进程管理命令
- 《Linux命令行与shell脚本》笔记--第5章:使用Linux环境变量
- Linux 下nice 函数用法提高一个进程的友善值
- linux系统编程之进程(八):守护进程详解及创建,daemon()使用
- Linux进程通信之匿名管道
- linux shell脚本编程笔记(四): 获取字符串长度的七种方法
- 通过指令“ps -l”查看进程信息