Node.js如何独立检查PID正在运行的进程? [英] Nodejs how to check independently a process is running by PID?

查看:1064
本文介绍了Node.js如何独立检查PID正在运行的进程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 child_process 生成一个子进程并从中获取返回PID。我需要通过其PID管理此子进程。下面是我的代码:

I'm using child_process to spawn a child process and get return PID from it. I need to manage this child process by its PID. Below is my code:

const childProcess = require('child_process');

let options = ['/c', arg1, arg2];

const myProcess = childProcess.spawn('cmd.exe', options, {
    detached: false,
    shell: false
});

let pid = myProcess.pid;

在运行时,如果过程是,我想使用PID来从外部独立验证是否运行(完成/杀死)。我想知道如何执行此操作以及在Node.js中进行此验证的最佳方法是什么?我正在Windows环境中运行应用程序。

During run time, I want to use PID to validate independently from outside if the process is running or not (finished / killed). I want to know how to do this and what is the best way to make this validation in Nodejs?. I'm running application in Windows environment.

感谢任何建议,谢谢。

推荐答案

我发现了一个解决方案,建议使用正在运行模块。但是我不想为此目的将新模块安装到我的项目中,所以我创建了自己的 checkRunning()函数,如下所示:

I found out a solution as suggestion of is-running module. But I don't want to install new module into my project just for this purpose, so I created my own checkRunning() function as below:

// Return true if process following pid is running
checkRunning(pid) {
    try {
        return process.kill(pid, 0);
    } catch (error) {
        console.error(error);
        return error.code === 'EPERM';
    }
}

在Nodejs文档中关注 process.kill(pid [,signal]),我可以使用 process.kill( )检查具有特定 signal 参数的进程是否存在,值为0(不终止进程作为函数名)。

Following the Nodejs document about process.kill(pid[, signal]), I can use process.kill() to check the existence of process with specific signal argument is value 0 (not killing process as function name).

我制作了一份文件副本:

I make a copy of the document said:


作为特殊情况,则可以使用信号0来测试进程是否存在

As a special case, a signal of 0 can be used to test for the existence of a process

这篇关于Node.js如何独立检查PID正在运行的进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆