简体   繁体   中英

Nodejs how to check independently a process is running by 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;

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.

Any suggestion is appreciated, thanks.

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';
    }
}

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:

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

可能这会有所帮助,npm 模块称为is-running https://npmjs.org/package/is-running,正如这里提到的 - https://stackoverflow.com/a/14884949/7927724

Here is a code fragment as a reference

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)
      })
    })
  },

which come from https://github.com/yibn2008/find-process/blob/master/lib/find_process.js

If you want to know when a child process exits, you can check the exit event

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}`);
});

For the related subject here the best packages

Check only by pid

https://www.npmjs.com/package/is-running

Search by pid, name patterns and different means packages:

https://www.npmjs.com/package/find-process

https://www.npmjs.com/package/ps-node

https://github.com/sindresorhus/process-exists

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM