【问题标题】:How to terminate ANY process using Node.js?如何使用 Node.js 终止任何进程?
【发布时间】:2022-01-20 09:52:04
【问题描述】:

Node 似乎没有系统调用来杀死进程(假设我知道它的 PID),或者是吗?

如果没有内置函数,什么是有效的跨平台方法?

【问题讨论】:

  • Nodejs 有一个process.kill() 方法,您可以使用该方法通过 pid 杀死进程。
  • @TGrif 好东西! terminate 库在后台也使用 process.kill,但它也处理一些需要多个终止信号的进程,并确保所有子进程也被终止。

标签: javascript node.js process pid kill


【解决方案1】:

The terminate library 似乎是为此目的而构建的。它是跨平台的。 (我在 Windows 和 MAC 上试过。)

Here is a working sample。 它还说明了如何通过 PORT 查找 PID。

例子:

const { promisify } = require('util');
/**
 * NOTE: as of 2021, terminate is still callback-based.
 */
const terminate = promisify(require('terminate'));

await terminate(myPid);

console.log('Process terminated.');

请注意,如果该进程不存在(或在任何其他问题的情况下),它将抛出,因此您可能需要相应地try/catch

【讨论】:

    猜你喜欢
    • 2014-06-30
    • 1970-01-01
    • 1970-01-01
    • 2010-10-27
    • 1970-01-01
    • 1970-01-01
    • 2010-11-26
    • 2010-09-12
    • 2013-12-23
    相关资源
    最近更新 更多