Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an arbitrary PID is running using Node.js?

Tags:

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.

like image 491
Zac B Avatar asked Jan 18 '13 01:01

Zac B


People also ask

How do you check if node is running or not?

To check the node server running by logging in to the system In windows you can simply go to the Task Manager and check for node in the application list. If it is there then it is running in the machine.

What is createServer in node JS?

The createServer method creates a server on your computer: var http = require('http'); http. createServer(function (req, res) { res.

What is PID in node JS?

Syntax: process.pid. Return Value: This property returns an integer value specifying the PID of the process. Below examples illustrate the use of process.pid property in Node.js: Example: // Node.js program to demonstrate the.

What is CWD node?

cwd() returns the current working directory, i.e. the directory from which you invoked the node command. __dirname returns the directory name of the directory containing the JavaScript source code file.


2 Answers

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;   } } 
like image 124
Shahar Avatar answered Sep 19 '22 17:09

Shahar


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

like image 42
Noah Avatar answered Sep 20 '22 17:09

Noah