Node.js 如何杀死所有进程
process.kill(pid[, signal]) 是Node.js中的内置技术,用于向进程发送消息,pid(进程ID)和signal(信号)以字符串的形式提供。
语法:
process.kill(pid[, signal])
边界: 此技术承认两个边界,如上所引用并在下面显示:
- pid: 此边界保存交互ID。
- signal: 此边界保存字符串设计。
- signal names: 这些是以字符串形式呈现的。
- SIGTERM
- SIGINT
- SIGHUP
注意: 如果没有指定信号,则默认为“SIGTERM”。
- “SIGTERM”和“SIGINT”信号在非Windows平台上有默认的处理程序,它们在退出时重置终端模式并带有代码128 +信号号。如果安装了其中一个信号的侦听器,则会删除node.js上的默认行为。
- 当控制台窗口关闭时,会产生“SIGHUP”。
返回值: 如果目标pid不存在或不存在,则process.kill()方法将引发错误。如果pid存在并且可以用作目标进程的测试,则该方法返回布尔值0。对于Windows用户,如果pid用于终止一组进程,则该方法也会抛出错误。
下面的示例显示了在Node.js中使用process.kill()属性的用法。
示例1:
index.js
// Node.js program to show the
// process.kill(pid[, signal]) strategy
// Printing process signal recognized
const displayInfo = () => {
console.log('Receiving SIGINT signal in nodeJS.');
}
// Starting a cycle
process.on('SIGINT', displayInfo);
setTimeout(() => {
console.log('Exiting.');
process.exit(0);
}, 100);
// kill the cycle with pid and sign = 'SIGINT'
process.kill(process.pid, 'SIGINT');
运行应用程序:
node index.js
输出:
示例2:
index.js
// Node.js program to exhibit the
// process.kill(pid[, signal]) technique
// Printing process signal recognized
const displayInfo = () => {
console.log('Acknowledged SIGHUP signal in nodeJS.');
}
// Starting an interaction
process.on('SIGHUP', displayInfo);
setTimeout(() => {
console.log('Exiting.');
process.exit(0);
}, 100);
// kill the cycle with pid and sign = 'SIGHUP'
process.kill(process.pid, 'SIGHUP');
运行应用程序:
node index.js
输出: