gpt4 book ai didi

python - Node.js:无法处理从 process.kill() 发送的 SIGINT

转载 作者:太空宇宙 更新时间:2023-11-03 18:10:33 25 4
gpt4 key购买 nike

我在 Windows 8.1 x64 上使用 Node.js v0.10.31。我注意到对于处理 SIGINT 的进程(node.js 或 python 脚本)处理程序,当信号通过process.kill(PID, "SIGINT")从另一个node.js进程发送时,处理程序不会被调用,从而导致它终止。不过,我确实验证了如果通过按 CTRL-C 发送 SIGINT,则处理程序会被调用。在控制台中。

这是处理 SIGINT 的 Node.js 脚本( CoffeeScript ):

process.on 'SIGINT', -> console.log "SIGINT handled"
process.stdin.pipe(process.stdout)
console.log "PID: #{process.pid}"

控制台输出:

PID: 6916
SIGINT handled (this happens when pressing ctrl-c in console)
SIGINT handled (this happens when pressing ctrl-c in console)
# process terminates when another process calls process.kill(6916, 'SIGINT')

这是一个处理 SIGINT 的 python 脚本,也被node.js无条件杀死process.kill(PID, 'SIGINT') :

from signal import signal, SIGINT
import os
import time

def handler(signum, frame):
print "signal handled:", signum,
raise KeyboardInterrupt

signal(SIGINT, handler)

print "PID: ", os.getpid()
while True:
try:
time.sleep(1e6)
except KeyboardInterrupt:
print " KeyboardInterrupt handled"

控制台输出:

PID:  6440
signal handled:2 KeyboardInterrupt handled (this happens when pressing ctrl-c in console)
signal handled:2 KeyboardInterrupt handled (this happens when pressing ctrl-c in console)
# process terminated by another node.js script's process.kill(6440, 'SIGINT')

为什么没有调用处理程序?

最佳答案

看来发送SIGINT并不是Node.js的问题,而是Windows平台的问题。这是因为当我从 python 程序发送 SIGINT 时,它也会无条件终止处理 SIGINT 事件的进程:

os.kill(pid, signal.SIGINT)

幸运的是,Python 更好地记录了这一点:

os.kill(pid, sig)

Send signal sig to the process pid. Constants for the specific signals available on the host platform are defined in the signal module.

Windows: The signal.CTRL_C_EVENT and signal.CTRL_BREAK_EVENT signals are special signals which can only be sent to console processes which share a common console window, e.g., some subprocesses. Any other value for sig will cause the process to be unconditionally killed by the TerminateProcess API, and the exit code will be set to sig. The Windows version of kill() additionally takes process handles to be killed.

关于python - Node.js:无法处理从 process.kill() 发送的 SIGINT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26053813/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com