-->

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

2019-10-21 01:48发布

我使用的Windows 8.1 x64的Node.js的v0.10.31。 我注意到一个过程(一个Node.js的或Python脚本),处理SIGINT处理程序,处理程序不是当信号从另一个Node.js的过程叫做发送process.kill(PID, "SIGINT")和从而导致它终止。 不过我确实验证,如果SIGINT是按发送的处理程序被称为CTRL-C控制台。

下面是处理Node.js的脚本SIGINT (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')

而这里的一个处理一个python脚本SIGINT ,这也是由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')

为什么不处理函数调用?

Answer 1:

现在看来似乎不是发送Node.js的问题SIGINT ,而是一个Windows平台的问题。 这是因为当我发送SIGINT从Python程序,它也无条件终止该处理过程SIGINT事件:

os.kill(pid, signal.SIGINT)

幸运的是,Python的文档这更好:

os.kill(PID,SIG)

发送信号sig到进程的PID。 在主机平台上可用的特定信号的常量信号模块中定义。

Windows上:signal.CTRL_C_EVENT和signal.CTRL_BREAK_EVENT信号只能被发送到控制台,它共用一个控制台窗口,如流程,子流程的一些特殊信号。 对于SIG任何其他值会导致进程在了TerminateProcess API无条件地杀害了,并且退出代码将被设置为SIG的。 杀的Windows版本()还需要处理处理被杀害。



文章来源: Node.js: SIGINT sent from process.kill() can't be handled