Last active
August 29, 2015 14:10
-
-
Save jbielick/e5ee2ef638ccf18cbd88 to your computer and use it in GitHub Desktop.
Example of Node.js forking and maintaining debug port for worker.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var path = require('path'); | |
var child_process = require('child_process'); | |
var currentFork; | |
var timesStarted = 0; | |
function fork(){ | |
var args = process.argv.slice(2), | |
execArgs = process.execArgv, | |
isDebug = process.execArgv.indexOf('--debug'); | |
// rudimentary example of making sure we bind to a different | |
// debug port than the master process | |
if (isDebug > -1) { | |
execArgs.splice(isDebug, 1); | |
execArgs.push('--debug=5859'); | |
} | |
// fork this file with args + '--worker' and sameish execArgs | |
currentFork = child_process.fork(__filename, args); | |
timesStarted++; | |
currentFork.on('close', fork); | |
} | |
setInterval(function failsafe() { | |
if (timesStarted > 1) { | |
console.error("loop detected"); | |
currentFork.kill(); | |
process.exit(0); | |
} | |
timesStarted = 0; | |
}, 500); | |
// fork if this is the master | |
// process will not have .send if it isn't a fork | |
if (!process.send) { | |
fork(); | |
// cycle fork simulation | |
setInterval(function() { | |
currentFork.kill(); | |
}, 3000); | |
} | |
/* | |
results: | |
┌[josh@jarvice] [130] | |
└[~/code/clustertest]> node --debug app.js | |
Debugger listening on port 5858 -- this is the master | |
Debugger listening on port 5859 -- fork | |
Debugger listening on port 5859 -- ^^ | |
Debugger listening on port 5859 | |
Debugger listening on port 5859 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment