在Windows操作系统上,Python如何发送SIGINT信号给子进程?

3

我读了很多stackoverflow上的问题,但它们都太旧了,对我没有帮助。 我有一个子进程,并想发送CTRL_C_EVENT信号来停止它。我不想直接杀掉它。 以下是我的代码:

import subprocess
import os
import signal

CREATE_NO_WINDOW = 0x08000000
'''
I tried these too but i failed.
creationflags=CREATE_NO_WINDOW | CREATE_NEW_PROCESS_GROUP | DETACHED_PROCESS
CREATE_NEW_PROCESS_GROUP = 0x00000200
DETACHED_PROCESS = 0x00000008
'''

cmd = 'my cmd arguments'
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,universal_newlines=True,shell=True,creationflags=CREATE_NO_WINDOW)
test = 0
for line in process.stdout:
    test += 1
    if (test > 60):
        os.kill(process.pid, signal.CTRL_C_EVENT)
        #This fails too
        #process.send_signal(signal.CTRL_C_EVENT)
    else:
        print(line)

这里是异常:

OSError: [WinError 6] The handler is invalid

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\xxxxxxx\Desktop\xxxxx\test subprocess.py", line 16, in <module>
    os.kill(process.pid, signal.CTRL_C_EVENT)
SystemError: <built-in function kill> returned a result with an error set
1个回答

0

我认为这是因为你的进程仍在使用中,由于 for line in process.stdout:

你可能需要先退出for循环然后发送CTRL_C_EVENT信号来停止它

尝试像这样做:

import subprocess
import os
import signal

CREATE_NO_WINDOW = 0x08000000
'''
I tried these too but i failed.
creationflags=CREATE_NO_WINDOW | CREATE_NEW_PROCESS_GROUP | DETACHED_PROCESS
CREATE_NEW_PROCESS_GROUP = 0x00000200
DETACHED_PROCESS = 0x00000008
'''

cmd = 'my cmd arguments'
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,universal_newlines=True,shell=True,creationflags=CREATE_NO_WINDOW)
test = 0

CTRL_C_EVENT_is_required=False

for line in process.stdout:
    test += 1
    if (test > 60):
        CTRL_C_EVENT_is_required=True
        break
    else:
        print(line)

if CTRL_C_EVENT_is_required==True:
    os.kill(process.pid, signal.CTRL_C_EVENT)

我仍然收到相同的错误。我尝试了 time.sleep(20) 并发送了 os.kill ctrl_cl_event 信号,但结果相同。 - sword1st

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接