简体   繁体   English

Python子进程中的Shell脚本.Popen不会终止子级

[英]Shell script in Python subprocess.Popen does not terminate child

I have an issue with interrupting the subprocess.Popen This is the setup: 我有一个中断subprocess.Popen的问题,这是安装程序:

I have a Tkinter gui and it is running a another python script using the Popen . 我有一个Tkinter gui,它正在使用Popen运行另一个python脚本。 This inner script (let's call it running script ) is running a shell shell script that is executing a piece of C++ code using a Popen so the hierarchical structure is looking like this: 这个内部脚本(我们称其为running script )正在运行一个shell脚本,该脚本正在使用Popen执行一段C ++代码,因此层次结构如下所示:

GUI
\running_script
 \shell-script
  \c++

running_script works so that if it receives an interrupt, it sends SIGINT to shell-script . running_script起作用,以便在接收到中断时将SIGINT发送到shell-script If i run a shell_script with my piece of C++ code with the running_script alone and do a CRTL+C everything works like a charm. 如果我仅使用shell_script来运行带有我的C ++代码的running_script并执行CRTL + C,那么一切都将像一个魅力。 However if i do it with GUI running the running_script as Popen, SIGINT is sent to the running_script is receives it properly and sends the interrupt signal to shell-script , but instead of terminating the inner process(being c++ code), the shell-script terminates itself and the C++ process continues running, as it was ran in the background, but it was not. 但是,如果我使用在running_script运行running_script GUI来执行此running_script ,则SIGINT发送到running_script会正确接收它,并将中断信号发送到shell-script ,但不是终止内部进程(是c ++代码),而是使用shell-script终止自身,并且C ++进程继续运行,因为它在后台运行,但不是。 When I execute ps -xaf the tree looks like this: 当我执行ps -xaf ,树看起来像这样:

GUI
\running_script
 \shell-script <defunct>
c++

So to reiterate, when i run it without the GUI it works like a charm, but with GUI it behaves as explained above. 重申一下,当我在没有GUI的情况下运行它时,它就像一个魅力,但在GUI的情况下,其行为如上所述。 I've tried sending shell-command a SIGTERM instead of SIGINT as well, the result is the same. 我也尝试向shell-command发送SIGTERM而不是SIGINT,结果是相同的。

You could catch SIGINT in the shell script and make it send SIGINT to the c++ program, eg: 您可以在shell脚本中捕获SIGINT并将其发送到C ++程序,例如:

#!/bin/bash
./cpp_program &
procpid=$!
function killit() {
    kill -SIGINT $procpid
}
trap killit SIGINT
......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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