process.js
* @module greppy/helper/process
* @author Hermann Mayer <hermann.mayer92@gmail.com>
var number = require('../extension/datatype/number');
* Find all child process ids for a given process id.
* @param {String} pid - Parent pid to search childs for
Process.prototype.findChilds = function(pid)
fs.readdirSync('/proc').forEach(function(proc) {
if (!proc.match(/^[0-9]*$/) && pid != proc) {
if (!fs.existsSync('/proc/' + proc + '/stat')) {
var stat = fs.readFileSync('/proc/' + proc + '/stat', 'ascii');
var parent = stat.split(' ')[3];
* Get the memory usage of the given process ids.
* @param {Array} pids - Pids to get memory usage for
Process.prototype.getMemoryUsage = function(pids)
if (!fs.existsSync('/proc/' + pid + '/status')) {
var status = fs.readFileSync('/proc/' + pid + '/status', 'ascii');
var rss = (new RegExp('^VmRSS:(.+)', 'mgi')).exec(status);
rss = parseInt(rss.split(new RegExp('\\s')).slice(-2)[0]);
* Check if the given process id exists and is running.
* @param {Integer} pid - Process id
Process.prototype.isRunning = function(pid)
if (!fs.existsSync('/proc/' + pid + '/status')) {
* Get the path to the process id file of a context.
* @param {String} path - Path to the application
* @param {String} context - Name of the context
Process.prototype.getPidPathForContext = function(path, context)
return (require('path')).normalize(path + '/var/run/' + context + '.pid');
* Get the process for a given context.
* @param {String} path - Path of the application
* @param {String} context - Name of the context to check
Process.prototype.getPidForContext = function(path, context)
path = this.getPidPathForContext(path, context);
if (!fs.existsSync(path) || !fs.statSync(path).isFile()) {
return fs.readFileSync(path, 'utf8');
* Check if the given context is running.
* @param {String} path - Path of the application
* @param {String} context - Name of the context to check
Process.prototype.isContextRunning = function(path, context)
path = this.getPidPathForContext(path, context);
if (!fs.existsSync(path) || !fs.statSync(path).isFile()) {
return this.isRunning(fs.readFileSync(path, 'utf8'));
* Get the state as object for a given context.
* @param {String} path - Path of the application
* @param {String} context - Name of the context to check
Process.prototype.getContextState = function(path, context)
running : this.isContextRunning(path, context),
pid : this.getPidForContext(path, context),
file : this.getPidPathForContext(path, context)
* @param {Integer} pid - Process id to kill
* @param {Integer|String} [signal] - Signal to send (default: SIGINT|2)
* @param {Function} callback - Function to call on finish
Process.prototype.kill = function(pid, signal, callback)
if ('function' === typeof signal) {
var child = (require('child_process')).spawn('kill', [
child.on('close', function(code) {
return callback && callback();