4

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.

ThanhPhanLe
  • 1,315
  • 3
  • 14
  • 25
  • possible duplicate of https://stackoverflow.com/questions/21255202/checking-if-a-child-process-is-running – A. M. Jul 31 '19 at 08:01
  • @A.M. https://stackoverflow.com/questions/21255202/checking-if-a-child-process-is-running is not my expected answer. I want to validate process from outside not listen `exit` event – ThanhPhanLe Jul 31 '19 at 08:08

5 Answers5

5

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

ThanhPhanLe
  • 1,315
  • 3
  • 14
  • 25
2

Probably this will help, npm module called is-running https://npmjs.org/package/is-running as was mentioned here - https://stackoverflow.com/a/14884949/7927724

1

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}`);
});
A. M.
  • 384
  • 1
  • 6
  • Thank @A. M. but this is not my expected answer. I want to validate process from outside independently, not listening `exit` event – ThanhPhanLe Jul 31 '19 at 08:11
0

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

sinbar
  • 933
  • 2
  • 7
  • 25
  • Thank @sinbar. but this is not my expected answer. I want to validate process from outside independently, not listening `close` event – ThanhPhanLe Jul 31 '19 at 09:01
  • That's not listen `close` event, the point is `'WMIC path win32_process get Name,Processid,ParentProcessId,Commandline,ExecutablePath'`.It spawn a `cmd` process and run a shell command in it and get the output: `proc.stdout.on('data', data => { lines.push(data.toString()) })` – sinbar Jul 31 '19 at 09:03
  • Oh, I don't want to listen output from `data` event also – ThanhPhanLe Jul 31 '19 at 09:05
0

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

Mohamed Allal
  • 17,920
  • 5
  • 94
  • 97