Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 395
TLePhan Avatar asked Oct 28 '25 14:10

TLePhan


1 Answers

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

like image 176
TLePhan Avatar answered Oct 31 '25 03:10

TLePhan