[英]Nodejs how to check independently a process is running by PID?
我正在使用child_process
来生成一个子进程并从中获取返回 PID。 我需要通过它的 PID 来管理这个子进程。 下面是我的代码:
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从外部独立验证进程是否正在运行(已完成/已终止)。 我想知道如何执行此操作以及在 Nodejs 中进行此验证的最佳方法是什么? 我在 Windows 环境中运行应用程序。
任何建议表示赞赏,谢谢。
我发现了一个解决方案作为正在运行的模块的建议。 但我不想为此目的将新模块安装到我的项目中,所以我创建了自己的checkRunning()
函数,如下所示:
// 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';
}
}
遵循关于process.kill(pid[, signal])的 Nodejs 文档,我可以使用process.kill()
检查具有特定signal
参数值为 0 的进程的存在(不杀死进程作为函数名称)。
我复印了一份文件说:
作为一种特殊情况,信号为 0 可用于测试进程是否存在
可能这会有所帮助,npm 模块称为is-running https://npmjs.org/package/is-running,正如这里提到的 - https://stackoverflow.com/a/14884949/7927724
这是一个代码片段作为参考
win32 (cond) {
return new Promise((resolve, reject) => {
const cmd = 'WMIC path win32_process get Name,Processid,ParentProcessId,Commandline,ExecutablePath'
const lines = []
const proc = utils.spawn('cmd', ['/c', cmd], { detached: false, windowsHide: true })
proc.stdout.on('data', data => {
lines.push(data.toString())
})
proc.on('close', code => {
if (code !== 0) {
return reject(new Error('Command \'' + cmd + '\' terminated with code: ' + code))
}
let list = utils.parseTable(lines.join('\n'))
.filter(row => {
if ('pid' in cond) {
return row.ProcessId === String(cond.pid)
} else if (cond.name) {
if (cond.strict) {
return row.Name === cond.name || (row.Name.endsWith('.exe') && row.Name.slice(0, -4) === cond.name)
} else {
// fix #9
return matchName(row.CommandLine || row.Name, cond.name)
}
} else {
return true
}
})
.map(row => ({
pid: parseInt(row.ProcessId, 10),
ppid: parseInt(row.ParentProcessId, 10),
// uid: void 0,
// gid: void 0,
bin: row.ExecutablePath,
name: row.Name,
cmd: row.CommandLine
}))
resolve(list)
})
})
},
来自https://github.com/yibn2008/find-process/blob/master/lib/find_process.js
如果想知道子进程什么时候退出,可以查看exit
事件
const { spawn } = require('child_process');
const bat = spawn('cmd.exe', ['/c', 'my.bat']);
bat.stdout.on('data', (data) => {
console.log(data.toString());
});
bat.stderr.on('data', (data) => {
console.log(data.toString());
});
bat.on('exit', (code) => {
console.log(`Child exited with code ${code}`);
});
对于这里的相关主题,最好的包
https://www.npmjs.com/package/is-running
https://www.npmjs.com/package/find-process
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.