如何使用Node.js检查任意PID是否正在运行?

时间:2022-12-04 19:23:51

Is there some way to check if an arbitrary PID is running or alive on the system, using Node.js? Assume that the Node.js script has the appropriate permissions to read /proc or the Windows equivalent.

有没有办法使用Node.js检查系统上的任意PID是运行还是活动?假设Node.js脚本具有读取/ proc或Windows等效项的适当权限。

This could be done either synchronously:

这可以同步完成:

if (isAlive(pid)) { //do stuff }

Or asynchronously:

或异步:

getProcessStatus(pid, function(status) {
    if (status === "alive") { //do stuff }
}

Note that I'm hoping to find a solution for this that works with an arbitrary system PID , not just the PID of a running Node.js process.

请注意,我希望找到一个适用于任意系统PID的解决方案,而不仅仅是运行Node.js进程的PID。

3 个解决方案

#1


17  

I needed to check for running pid's in a project as well. I took this answer of using kill -0 <PID> and wrapped it up in a module called is-running https://npmjs.org/package/is-running

我还需要在项目中检查运行pid的情况。我接受了使用kill -0 的答案并将其包装在名为is-running https://npmjs.org/package/is-running的模块中

npm install is-running

npm install正在运行

#2


13  

Seems like you can call process.kill(pid, 0) and wrap it up in a try/catch.

好像你可以调用process.kill(pid,0)并将它包装在try / catch中。

http://nodejs.org/api/process.html#process_process_kill_pid_signal - "Will throw an error if target does not exist, and as a special case, a signal of 0 can be used to test for the existence of a process."

http://nodejs.org/api/process.html#process_process_kill_pid_signal - “如果目标不存在,将抛出错误,作为一种特殊情况,0的信号可用于测试进程是否存在。”

#3


-1  

I'm not an expert here, but could you not spawn a child process to check the status with a command line tool?

我不是这里的专家,但您是否可以使用命令行工具生成子进程来检查状态?

#1


17  

I needed to check for running pid's in a project as well. I took this answer of using kill -0 <PID> and wrapped it up in a module called is-running https://npmjs.org/package/is-running

我还需要在项目中检查运行pid的情况。我接受了使用kill -0 的答案并将其包装在名为is-running https://npmjs.org/package/is-running的模块中

npm install is-running

npm install正在运行

#2


13  

Seems like you can call process.kill(pid, 0) and wrap it up in a try/catch.

好像你可以调用process.kill(pid,0)并将它包装在try / catch中。

http://nodejs.org/api/process.html#process_process_kill_pid_signal - "Will throw an error if target does not exist, and as a special case, a signal of 0 can be used to test for the existence of a process."

http://nodejs.org/api/process.html#process_process_kill_pid_signal - “如果目标不存在,将抛出错误,作为一种特殊情况,0的信号可用于测试进程是否存在。”

#3


-1  

I'm not an expert here, but could you not spawn a child process to check the status with a command line tool?

我不是这里的专家,但您是否可以使用命令行工具生成子进程来检查状态?