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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With