相关疑难解决方法(0)

Ctrl-C如何终止子进程?

我试图了解CTRL+ 如何C终止子进程而不是父进程.我在一些脚本shell中看到了这种行为,比如bash你可以在哪里开始一个长时间运行的进程然后通过输入来终止它CTRL- C然后控制返回到shell.

你能解释它是如何工作的,特别是为什么父(shell)进程没有终止?

shell是否必须对CTRL+ C事件进行一些特殊处理,如果是,它究竟是做什么的?

bash shell process sh

63
推荐指数
3
解决办法
6万
查看次数

使用 KeyboardInterrupt 终止子进程

我正在使用 Python 使用 subprocess 模块调用 C++ 程序。由于程序需要一些时间来运行,我希望能够使用 Ctrl+C 来终止它。我在 StackOverflow 上看到了一些关于此的问题,但似乎没有一个解决方案对我有用。

我想要的是在 KeyboardInterrupt 上终止子进程。这是我拥有的代码(类似于其他问题中的建议):

import subprocess

binary_path = '/path/to/binary'
args = 'arguments' # arbitrary

call_str = '{} {}'.format(binary_path, args)

proc = subprocess.Popen(call_str)

try:
    proc.wait()
except KeyboardInterrupt:
    proc.terminate()
Run Code Online (Sandbox Code Playgroud)

但是,如果我运行它,代码会挂起,等待进程结束并且永远不会注册 KeyboardInterrupt。我也尝试了以下方法:

import subprocess
import time

binary_path = '/path/to/binary'
args = 'arguments' # arbitrary

call_str = '{} {}'.format(binary_path, args)

proc = subprocess.Popen(call_str)
time.sleep(5)
proc.terminate()
Run Code Online (Sandbox Code Playgroud)

此代码片段在终止程序时工作正常,因此问题不是发送到终止的实际信号。

如何更改代码以便子进程可以在 KeyboardInterrupt 上终止?

我正在运行 Python 2.7 和 Windows 7 64 位。提前致谢!

我尝试过的一些相关问题:

Python子进程Ctrl+C

在 KeyboardInterrupt 后杀死 subprocess.call

当python进程被杀死时杀死子进程?

python windows subprocess interrupt terminate

4
推荐指数
1
解决办法
5110
查看次数

标签 统计

bash ×1

interrupt ×1

process ×1

python ×1

sh ×1

shell ×1

subprocess ×1

terminate ×1

windows ×1