我在Windows 8.1 x64上使用Node.js v0.10.31。我注意到,对于处理SIGINT
处理程序的进程(node.js或python脚本),当process.kill(PID, "SIGINT")
从另一个node.js进程发送信号时,不会调用该处理程序,从而导致它终止。然而,我确实验证了,如果通过在控制台中按CTRL-C
发送SIGINT,则会调用处理程序。
这是处理SIGINT
(CoffeeScript)的Node.js脚本:
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')
为什么没有调用处理程序?
似乎不是Node.js发送SIGINT
的问题,而是Windows平台的问题。这是因为当我从python程序发送SIGINT
时,它也会无条件地终止处理SIGINT
事件的进程:
os.kill(pid, signal.SIGINT)
幸运的是,Python更好地记录了这一点:
os.kill(pid,sig)
向进程pid发送信号sig。的常量主机平台上可用的特定信号在信号模块。
窗口:信号。CTRL_C_EVENT和信号。CTRL_BREAK_EVENT信号是只能发送到控制台进程的特殊信号共享一个通用控制台窗口,例如一些子流程任何其他sig的值将导致进程被无条件地终止TerminateProcess API,退出代码将设置为sigWindows版本的kill()还将进程句柄设为被杀害。