min*_*xia 5 windows signals child-process node.js
嗨,我正在使用child_process.spwan来启动在Windows上运行python脚本的子进程。该脚本侦听SIGINT以正常退出。但是Windows不支持信号,并且所有节点都在模拟。因此,child_process.kill('SIGINT')在Windows上实际上是无条件终止进程(没有正常退出,没有调用python的SIGTERM / SIGINT处理程序)。同样ctrl+c向stdin 写入字符也不起作用。
当我研究Python API时,我得到了可以满足需求的CTRL_BREAK_EVENT和CTRL_C_EVENT。我想知道节点是否具有类似的特定于平台的API?
相关文章,但不起作用: 如何 使用stdin.write()将控件C的node.js和child_processes 发送给crtl + c到node.js产生的子进程?
您可以使用 IPC 消息向子进程发出信号,表明该停止并正常终止了。下面的方法用于process.on('message')在子进程中侦听来自父进程的消息并将child_process.send()消息从父进程发送到子进程。
下面的代码设置了 1 分钟超时,如果子进程挂起或需要很长时间才能完成,则退出。
py-script-wrapper.js
// Handle messages sent from the Parent
process.on('message', (msg) => {
if (msg.action === 'STOP') {
// Execute Graceful Termination code
process.exit(0); // Exit Process with no Errors
}
});
Run Code Online (Sandbox Code Playgroud)
父进程
const cp = require('child_process');
const py = cp.fork('./py-script-wrapper.js');
// On 'SIGINT'
process.on('SIGINT', () => {
// Send a message to the python script
py.send({ action: 'STOP' });
// Now that the child process has gracefully terminated
// exit parent process without error
py.on('exit', (code, signal) => {
process.exit(0);
});
// If the child took too long to exit
// Kill the child, and exit with a failure code
setTimeout(60000, () => {
py.kill();
process.exit(1);
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2394 次 |
| 最近记录: |