diff --git a/README.md b/README.md index 96856fb..a60e9aa 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,8 @@ var monitor = respawn(['node', 'server.js'], { // or -1 for infinite restarts sleep:1000, // time to sleep between restarts, kill:30000, // wait 30s before force killing after stopping - stdio: [...] // forward stdio options + stdio: [...], // forward stdio options + fork: true // fork instead of spawn }) monitor.start() // spawn and watch diff --git a/index.js b/index.js index e0b0b71..d73dbd4 100644 --- a/index.js +++ b/index.js @@ -1,5 +1,6 @@ var events = require('events') var spawn = require('child_process').spawn +var fork = require('child_process').fork var exec = require('child_process').exec var ps = require('ps-tree') var util = require('util') @@ -51,7 +52,11 @@ var Monitor = function(command, opts) { this.stdio = opts.stdio this.stdout = opts.stdout this.stderr = opts.stderr + this.silent = opts.silent this.windowsVerbatimArguments = opts.windowsVerbatimArguments + this.spawnFn = opts.fork + ? fork + : spawn this.crashed = false this.sleep = typeof opts.sleep === 'function' ? opts.sleep : defaultSleep(opts.sleep) @@ -106,12 +111,13 @@ Monitor.prototype.start = function() { var loop = function() { var cmd = typeof self.command === 'function' ? self.command() : self.command - var child = spawn(cmd[0], cmd.slice(1), { + var child = self.spawnFn(cmd[0], cmd.slice(1), { cwd: self.cwd, env: xtend(process.env, self.env), uid: self.uid, gid: self.gid, stdio: self.stdio, + silent: self.silent, windowsVerbatimArguments: self.windowsVerbatimArguments }) @@ -143,6 +149,10 @@ Monitor.prototype.start = function() { } } + child.on('message', function(message) { + self.emit('message', message) + }) + var clear = function() { if (self.child !== child) return false self.child = null diff --git a/test/apps/fork.js b/test/apps/fork.js new file mode 100644 index 0000000..7fadebb --- /dev/null +++ b/test/apps/fork.js @@ -0,0 +1 @@ +process.send({ foo: 'bar' }) diff --git a/test/index.js b/test/index.js index d18dc38..b83a011 100644 --- a/test/index.js +++ b/test/index.js @@ -7,6 +7,7 @@ var crash = path.join(__dirname, 'apps', 'crash.js') var run = path.join(__dirname, 'apps', 'run.js') var hello = path.join(__dirname, 'apps', 'hello-world.js') var env = path.join(__dirname, 'apps', 'env.js') +var fork = path.join(__dirname, 'apps', 'fork.js') var node = process.execPath test('restart', function(t) { @@ -290,3 +291,23 @@ test('restart using restart strategy function', function (t) { }) mon.start() }) + +test('fork', function(t) { + t.plan(1) + + var mon = respawn([fork], {fork:true, maxRestarts:1, sleep:1}) + var messages = [] + + mon.on('message', function(message) { + messages.push(message) + }) + + mon.on('stop', function() { + t.deepEqual(messages, [ + {foo: 'bar'}, + {foo: 'bar'} + ]) + }) + + mon.start() +})