26

Is there some way to check if an arbitrary PID is running or alive on the system, using Node.js? Assume that the Node.js script has the appropriate permissions to read /proc or the Windows equivalent.

This could be done either synchronously:

if (isAlive(pid)) { //do stuff }

Or asynchronously:

getProcessStatus(pid, function(status) {
    if (status === "alive") { //do stuff }
}

Note that I'm hoping to find a solution for this that works with an arbitrary system PID , not just the PID of a running Node.js process.

Zac B
  • 3,796
  • 3
  • 35
  • 52

2 Answers2

39

You can call process.kill(pid, 0) and wrap it up in a try/catch.

http://nodejs.org/api/process.html#process_process_kill_pid_signal -

"Will throw an error if target does not exist, and as a special case, a signal of 0 can be used to test for the existence of a process."

Example:

function pidIsRunning(pid) {
  try {
    process.kill(pid, 0);
    return true;
  } catch(e) {
    return false;
  }
}
joe
  • 3,752
  • 1
  • 32
  • 41
Shahar
  • 426
  • 1
  • 4
  • 3
  • For whoever needs to hear this today: Yes, this does work on Windows, even though other uses of `process.kill` aren't always what you expect (for example, `-2` does not send a `SIGINT` on Windows -- it just kills the process) – data princess May 22 '23 at 21:17
19

I needed to check for running pid's in a project as well. I took this answer of using kill -0 <PID> and wrapped it up in a module called is-running https://npmjs.org/package/is-running

npm install is-running

Community
  • 1
  • 1
Noah
  • 33,851
  • 5
  • 37
  • 32
  • +1 Doesn't spawn a child for killing. Just a question though, why do you require the module exec in your `index.js`? – hexacyanide Apr 03 '13 at 14:47
  • exec is left over from a previous version. It should go away – Noah Apr 03 '13 at 17:04
  • 1
    This works in simple situations, but be aware that *it will report processes don't exist if your user does not have permission to signal them*. For example, unless you are running as a root user, PID 1 (the root PID of the OS) and any system-level daemon PIDs will be reported as nonexistent. – Zac B Jul 10 '17 at 17:30
  • @ZacB on macOS at least, you get EPERM if the process exists but you don't have permission, and ESRCH if it doesn't exist – w00t Oct 16 '19 at 07:41
  • 1
    I believe a clean solution (not requiring another npm module) should be selected answer. – Kyeno Dec 13 '22 at 18:18
  • I'm very against using an NPM package for any simple task. – Soroush Bgm Feb 27 '23 at 00:24