diff --git a/doc/api/cluster.markdown b/doc/api/cluster.markdown index a1d30ef6001b8b..594dea0832908d 100644 --- a/doc/api/cluster.markdown +++ b/doc/api/cluster.markdown @@ -101,294 +101,219 @@ will be dropped and new connections will be refused. Node.js does not automatically manage the number of workers for you, however. It is your responsibility to manage the worker pool for your application's needs. -## cluster.schedulingPolicy - -The scheduling policy, either `cluster.SCHED_RR` for round-robin or -`cluster.SCHED_NONE` to leave it to the operating system. This is a -global setting and effectively frozen once you spawn the first worker -or call `cluster.setupMaster()`, whatever comes first. - -`SCHED_RR` is the default on all operating systems except Windows. -Windows will change to `SCHED_RR` once libuv is able to effectively -distribute IOCP handles without incurring a large performance hit. - -`cluster.schedulingPolicy` can also be set through the -`NODE_CLUSTER_SCHED_POLICY` environment variable. Valid -values are `"rr"` and `"none"`. - -## cluster.settings - -* {Object} - * `execArgv` {Array} list of string arguments passed to the Node.js - executable. (Default=`process.execArgv`) - * `exec` {String} file path to worker file. (Default=`process.argv[1]`) - * `args` {Array} string arguments passed to worker. - (Default=`process.argv.slice(2)`) - * `silent` {Boolean} whether or not to send output to parent's stdio. - (Default=`false`) - * `uid` {Number} Sets the user identity of the process. (See setuid(2).) - * `gid` {Number} Sets the group identity of the process. (See setgid(2).) - -After calling `.setupMaster()` (or `.fork()`) this settings object will contain -the settings, including the default values. - -It is effectively frozen after being set, because `.setupMaster()` can -only be called once. - -This object is not supposed to be changed or set manually, by you. - -## cluster.isMaster - -* {Boolean} -True if the process is a master. This is determined -by the `process.env.NODE_UNIQUE_ID`. If `process.env.NODE_UNIQUE_ID` is -undefined, then `isMaster` is `true`. - -## cluster.isWorker - -* {Boolean} -True if the process is not a master (it is the negation of `cluster.isMaster`). - -## Event: 'fork' +## Class: Worker -* `worker` {Worker object} +A Worker object contains all public information and method about a worker. +In the master it can be obtained using `cluster.workers`. In a worker +it can be obtained using `cluster.worker`. -When a new worker is forked the cluster module will emit a 'fork' event. -This can be used to log worker activity, and create your own timeout. +### Event: 'disconnect' - var timeouts = []; - function errorMsg() { - console.error("Something must be wrong with the connection ..."); - } +Similar to the `cluster.on('disconnect')` event, but specific to this worker. - cluster.on('fork', function(worker) { - timeouts[worker.id] = setTimeout(errorMsg, 2000); - }); - cluster.on('listening', function(worker, address) { - clearTimeout(timeouts[worker.id]); - }); - cluster.on('exit', function(worker, code, signal) { - clearTimeout(timeouts[worker.id]); - errorMsg(); + cluster.fork().on('disconnect', function() { + // Worker has disconnected }); -## Event: 'online' - -* `worker` {Worker object} +### Event: 'error' -After forking a new worker, the worker should respond with an online message. -When the master receives an online message it will emit this event. -The difference between 'fork' and 'online' is that fork is emitted when the -master forks a worker, and 'online' is emitted when the worker is running. +This event is the same as the one provided by `child_process.fork()`. - cluster.on('online', function(worker) { - console.log("Yay, the worker responded after it was forked"); - }); +In a worker you can also use `process.on('error')`. -## Event: 'listening' +[ChildProcess.send()]: child_process.html#child_process_child_send_message_sendhandle_callback -* `worker` {Worker object} -* `address` {Object} +### Event: 'exit' -After calling `listen()` from a worker, when the 'listening' event is emitted on -the server, a listening event will also be emitted on `cluster` in the master. +* `code` {Number} the exit code, if it exited normally. +* `signal` {String} the name of the signal (eg. `'SIGHUP'`) that caused + the process to be killed. -The event handler is executed with two arguments, the `worker` contains the worker -object and the `address` object contains the following connection properties: -`address`, `port` and `addressType`. This is very useful if the worker is listening -on more than one address. +Similar to the `cluster.on('exit')` event, but specific to this worker. - cluster.on('listening', function(worker, address) { - console.log("A worker is now connected to " + address.address + ":" + address.port); + var worker = cluster.fork(); + worker.on('exit', function(code, signal) { + if( signal ) { + console.log("worker was killed by signal: "+signal); + } else if( code !== 0 ) { + console.log("worker exited with error code: "+code); + } else { + console.log("worker success!"); + } }); -The `addressType` is one of: - -* `4` (TCPv4) -* `6` (TCPv6) -* `-1` (unix domain socket) -* `"udp4"` or `"udp6"` (UDP v4 or v6) - -## Event: 'disconnect' - -* `worker` {Worker object} +### Event: 'listening' -Emitted after the worker IPC channel has disconnected. This can occur when a -worker exits gracefully, is killed, or is disconnected manually (such as with -worker.disconnect()). +* `address` {Object} -There may be a delay between the `disconnect` and `exit` events. These events -can be used to detect if the process is stuck in a cleanup or if there are -long-living connections. +Similar to the `cluster.on('listening')` event, but specific to this worker. - cluster.on('disconnect', function(worker) { - console.log('The worker #' + worker.id + ' has disconnected'); + cluster.fork().on('listening', function(address) { + // Worker is listening }); -## Event: 'exit' - -* `worker` {Worker object} -* `code` {Number} the exit code, if it exited normally. -* `signal` {String} the name of the signal (eg. `'SIGHUP'`) that caused - the process to be killed. - -When any of the workers die the cluster module will emit the 'exit' event. - -This can be used to restart the worker by calling `.fork()` again. +It is not emitted in the worker. - cluster.on('exit', function(worker, code, signal) { - console.log('worker %d died (%s). restarting...', - worker.process.pid, signal || code); - cluster.fork(); - }); +### Event: 'message' -See [child_process event: 'exit'](child_process.html#child_process_event_exit). +* `message` {Object} -## Event: 'message' +Similar to the `cluster.on('message')` event, but specific to this worker. -* `worker` {Worker object} -* `message` {Object} +This event is the same as the one provided by `child_process.fork()`. -Emitted when any worker receives a message. +In a worker you can also use `process.on('message')`. -See -[child_process event: 'message'](child_process.html#child_process_event_message). +As an example, here is a cluster that keeps count of the number of requests +in the master process using the message system: -## Event: 'setup' + var cluster = require('cluster'); + var http = require('http'); -* `settings` {Object} + if (cluster.isMaster) { -Emitted every time `.setupMaster()` is called. + // Keep track of http requests + var numReqs = 0; + setInterval(function() { + console.log("numReqs =", numReqs); + }, 1000); -The `settings` object is the `cluster.settings` object at the time -`.setupMaster()` was called and is advisory only, since multiple calls to -`.setupMaster()` can be made in a single tick. + // Count requests + function messageHandler(msg) { + if (msg.cmd && msg.cmd == 'notifyRequest') { + numReqs += 1; + } + } -If accuracy is important, use `cluster.settings`. + // Start workers and listen for messages containing notifyRequest + var numCPUs = require('os').cpus().length; + for (var i = 0; i < numCPUs; i++) { + cluster.fork(); + } -## cluster.setupMaster([settings]) + Object.keys(cluster.workers).forEach(function(id) { + cluster.workers[id].on('message', messageHandler); + }); -* `settings` {Object} - * `exec` {String} file path to worker file. (Default=`process.argv[1]`) - * `args` {Array} string arguments passed to worker. - (Default=`process.argv.slice(2)`) - * `silent` {Boolean} whether or not to send output to parent's stdio. - (Default=`false`) + } else { -`setupMaster` is used to change the default 'fork' behavior. Once called, -the settings will be present in `cluster.settings`. + // Worker processes have a http server. + http.Server(function(req, res) { + res.writeHead(200); + res.end("hello world\n"); -Note that: + // notify master about the request + process.send({ cmd: 'notifyRequest' }); + }).listen(8000); + } -* any settings changes only affect future calls to `.fork()` and have no - effect on workers that are already running -* The *only* attribute of a worker that cannot be set via `.setupMaster()` is - the `env` passed to `.fork()` -* the defaults above apply to the first call only, the defaults for later - calls is the current value at the time of `cluster.setupMaster()` is called +### Event: 'online' -Example: +Similar to the `cluster.on('online')` event, but specific to this worker. - var cluster = require('cluster'); - cluster.setupMaster({ - exec: 'worker.js', - args: ['--use', 'https'], - silent: true - }); - cluster.fork(); // https worker - cluster.setupMaster({ - args: ['--use', 'http'] + cluster.fork().on('online', function() { + // Worker is online }); - cluster.fork(); // http worker - -This can only be called from the master process. -## cluster.fork([env]) +It is not emitted in the worker. -* `env` {Object} Key/value pairs to add to worker process environment. -* return {Worker object} +### worker.disconnect() -Spawn a new worker process. +In a worker, this function will close all servers, wait for the 'close' event on +those servers, and then disconnect the IPC channel. -This can only be called from the master process. +In the master, an internal message is sent to the worker causing it to call +`.disconnect()` on itself. -## cluster.disconnect([callback]) +Causes `.suicide` to be set. -* `callback` {Function} called when all workers are disconnected and handles are - closed +Note that after a server is closed, it will no longer accept new connections, +but connections may be accepted by any other listening worker. Existing +connections will be allowed to close as usual. When no more connections exist, +see [server.close()](net.html#net_event_close), the IPC channel to the worker +will close allowing it to die gracefully. -Calls `.disconnect()` on each worker in `cluster.workers`. +The above applies *only* to server connections, client connections are not +automatically closed by workers, and disconnect does not wait for them to close +before exiting. -When they are disconnected all internal handles will be closed, allowing the -master process to die gracefully if no other event is waiting. +Note that in a worker, `process.disconnect` exists, but it is not this function, +it is [disconnect](child_process.html#child_process_child_disconnect). -The method takes an optional callback argument which will be called when finished. +Because long living server connections may block workers from disconnecting, it +may be useful to send a message, so application specific actions may be taken to +close them. It also may be useful to implement a timeout, killing a worker if +the `disconnect` event has not been emitted after some time. -This can only be called from the master process. + if (cluster.isMaster) { + var worker = cluster.fork(); + var timeout; -## cluster.worker + worker.on('listening', function(address) { + worker.send('shutdown'); + worker.disconnect(); + timeout = setTimeout(function() { + worker.kill(); + }, 2000); + }); -* {Object} + worker.on('disconnect', function() { + clearTimeout(timeout); + }); -A reference to the current worker object. Not available in the master process. + } else if (cluster.isWorker) { + var net = require('net'); + var server = net.createServer(function(socket) { + // connections never end + }); - var cluster = require('cluster'); + server.listen(8000); - if (cluster.isMaster) { - console.log('I am master'); - cluster.fork(); - cluster.fork(); - } else if (cluster.isWorker) { - console.log('I am worker #' + cluster.worker.id); + process.on('message', function(msg) { + if(msg === 'shutdown') { + // initiate graceful close of any connections to server + } + }); } -## cluster.workers +### worker.id -* {Object} +* {Number} -A hash that stores the active worker objects, keyed by `id` field. Makes it -easy to loop through all the workers. It is only available in the master -process. +Each new worker is given its own unique id, this id is stored in the +`id`. -A worker is removed from cluster.workers after the worker has disconnected _and_ -exited. The order between these two events cannot be determined in advance. -However, it is guaranteed that the removal from the cluster.workers list happens -before last `'disconnect'` or `'exit'` event is emitted. +While a worker is alive, this is the key that indexes it in +cluster.workers - // Go through all workers - function eachWorker(callback) { - for (var id in cluster.workers) { - callback(cluster.workers[id]); - } - } - eachWorker(function(worker) { - worker.send('big announcement to all workers'); - }); +### worker.isConnected() -Should you wish to reference a worker over a communication channel, using -the worker's unique id is the easiest way to find the worker. +This function returns `true` if the worker is connected to its master via its IPC +channel, `false` otherwise. A worker is connected to its master after it's been +created. It is disconnected after the `disconnect` event is emitted. - socket.on('data', function(id) { - var worker = cluster.workers[id]; - }); +### worker.isDead() -## Class: Worker +This function returns `true` if the worker's process has terminated (either +because of exiting or being signaled). Otherwise, it returns `false`. -A Worker object contains all public information and method about a worker. -In the master it can be obtained using `cluster.workers`. In a worker -it can be obtained using `cluster.worker`. +### worker.kill([signal='SIGTERM']) -### worker.id +* `signal` {String} Name of the kill signal to send to the worker + process. -* {Number} +This function will kill the worker. In the master, it does this by disconnecting +the `worker.process`, and once disconnected, killing with `signal`. In the +worker, it does it by disconnecting the channel, and then exiting with code `0`. -Each new worker is given its own unique id, this id is stored in the -`id`. +Causes `.suicide` to be set. -While a worker is alive, this is the key that indexes it in -cluster.workers +This method is aliased as `worker.destroy()` for backwards compatibility. + +Note that in a worker, `process.kill()` exists, but it is not this function, +it is [kill](process.html#process_process_kill_pid_signal). ### worker.process @@ -405,24 +330,6 @@ Note that workers will call `process.exit(0)` if the `'disconnect'` event occurs on `process` and `.suicide` is not `true`. This protects against accidental disconnection. -### worker.suicide - -* {Boolean} - -Set by calling `.kill()` or `.disconnect()`, until then it is `undefined`. - -The boolean `worker.suicide` lets you distinguish between voluntary and accidental -exit, the master may choose not to respawn a worker based on this value. - - cluster.on('exit', function(worker, code, signal) { - if (worker.suicide === true) { - console.log('Oh, it was just suicide\' – no need to worry'). - } - }); - - // kill worker - worker.kill(); - ### worker.send(message[, sendHandle][, callback]) * `message` {Object} @@ -450,198 +357,293 @@ This example will echo back all messages from the master: }); } -### worker.kill([signal='SIGTERM']) +### worker.suicide -* `signal` {String} Name of the kill signal to send to the worker - process. +* {Boolean} -This function will kill the worker. In the master, it does this by disconnecting -the `worker.process`, and once disconnected, killing with `signal`. In the -worker, it does it by disconnecting the channel, and then exiting with code `0`. +Set by calling `.kill()` or `.disconnect()`, until then it is `undefined`. + +The boolean `worker.suicide` lets you distinguish between voluntary and accidental +exit, the master may choose not to respawn a worker based on this value. + + cluster.on('exit', function(worker, code, signal) { + if (worker.suicide === true) { + console.log('Oh, it was just suicide\' – no need to worry'). + } + }); + + // kill worker + worker.kill(); + +## Event: 'disconnect' + +* `worker` {Worker object} + +Emitted after the worker IPC channel has disconnected. This can occur when a +worker exits gracefully, is killed, or is disconnected manually (such as with +worker.disconnect()). + +There may be a delay between the `disconnect` and `exit` events. These events +can be used to detect if the process is stuck in a cleanup or if there are +long-living connections. + + cluster.on('disconnect', function(worker) { + console.log('The worker #' + worker.id + ' has disconnected'); + }); + +## Event: 'exit' + +* `worker` {Worker object} +* `code` {Number} the exit code, if it exited normally. +* `signal` {String} the name of the signal (eg. `'SIGHUP'`) that caused + the process to be killed. + +When any of the workers die the cluster module will emit the 'exit' event. + +This can be used to restart the worker by calling `.fork()` again. + + cluster.on('exit', function(worker, code, signal) { + console.log('worker %d died (%s). restarting...', + worker.process.pid, signal || code); + cluster.fork(); + }); + +See [child_process event: 'exit'](child_process.html#child_process_event_exit). + +## Event: 'fork' + +* `worker` {Worker object} + +When a new worker is forked the cluster module will emit a 'fork' event. +This can be used to log worker activity, and create your own timeout. + + var timeouts = []; + function errorMsg() { + console.error("Something must be wrong with the connection ..."); + } + + cluster.on('fork', function(worker) { + timeouts[worker.id] = setTimeout(errorMsg, 2000); + }); + cluster.on('listening', function(worker, address) { + clearTimeout(timeouts[worker.id]); + }); + cluster.on('exit', function(worker, code, signal) { + clearTimeout(timeouts[worker.id]); + errorMsg(); + }); + +## Event: 'listening' + +* `worker` {Worker object} +* `address` {Object} + +After calling `listen()` from a worker, when the 'listening' event is emitted on +the server, a listening event will also be emitted on `cluster` in the master. + +The event handler is executed with two arguments, the `worker` contains the worker +object and the `address` object contains the following connection properties: +`address`, `port` and `addressType`. This is very useful if the worker is listening +on more than one address. + + cluster.on('listening', function(worker, address) { + console.log("A worker is now connected to " + address.address + ":" + address.port); + }); + +The `addressType` is one of: + +* `4` (TCPv4) +* `6` (TCPv6) +* `-1` (unix domain socket) +* `"udp4"` or `"udp6"` (UDP v4 or v6) + +## Event: 'message' + +* `worker` {Worker object} +* `message` {Object} + +Emitted when any worker receives a message. + +See +[child_process event: 'message'](child_process.html#child_process_event_message). -Causes `.suicide` to be set. +## Event: 'online' -This method is aliased as `worker.destroy()` for backwards compatibility. +* `worker` {Worker object} -Note that in a worker, `process.kill()` exists, but it is not this function, -it is [kill](process.html#process_process_kill_pid_signal). +After forking a new worker, the worker should respond with an online message. +When the master receives an online message it will emit this event. +The difference between 'fork' and 'online' is that fork is emitted when the +master forks a worker, and 'online' is emitted when the worker is running. -### worker.disconnect() + cluster.on('online', function(worker) { + console.log("Yay, the worker responded after it was forked"); + }); -In a worker, this function will close all servers, wait for the 'close' event on -those servers, and then disconnect the IPC channel. +## Event: 'setup' -In the master, an internal message is sent to the worker causing it to call -`.disconnect()` on itself. +* `settings` {Object} -Causes `.suicide` to be set. +Emitted every time `.setupMaster()` is called. -Note that after a server is closed, it will no longer accept new connections, -but connections may be accepted by any other listening worker. Existing -connections will be allowed to close as usual. When no more connections exist, -see [server.close()](net.html#net_event_close), the IPC channel to the worker -will close allowing it to die gracefully. +The `settings` object is the `cluster.settings` object at the time +`.setupMaster()` was called and is advisory only, since multiple calls to +`.setupMaster()` can be made in a single tick. -The above applies *only* to server connections, client connections are not -automatically closed by workers, and disconnect does not wait for them to close -before exiting. +If accuracy is important, use `cluster.settings`. -Note that in a worker, `process.disconnect` exists, but it is not this function, -it is [disconnect](child_process.html#child_process_child_disconnect). +## cluster.disconnect([callback]) -Because long living server connections may block workers from disconnecting, it -may be useful to send a message, so application specific actions may be taken to -close them. It also may be useful to implement a timeout, killing a worker if -the `disconnect` event has not been emitted after some time. +* `callback` {Function} called when all workers are disconnected and handles are + closed - if (cluster.isMaster) { - var worker = cluster.fork(); - var timeout; +Calls `.disconnect()` on each worker in `cluster.workers`. - worker.on('listening', function(address) { - worker.send('shutdown'); - worker.disconnect(); - timeout = setTimeout(function() { - worker.kill(); - }, 2000); - }); +When they are disconnected all internal handles will be closed, allowing the +master process to die gracefully if no other event is waiting. - worker.on('disconnect', function() { - clearTimeout(timeout); - }); +The method takes an optional callback argument which will be called when finished. - } else if (cluster.isWorker) { - var net = require('net'); - var server = net.createServer(function(socket) { - // connections never end - }); +This can only be called from the master process. - server.listen(8000); +## cluster.fork([env]) - process.on('message', function(msg) { - if(msg === 'shutdown') { - // initiate graceful close of any connections to server - } - }); - } +* `env` {Object} Key/value pairs to add to worker process environment. +* return {Worker object} -### worker.isDead() +Spawn a new worker process. -This function returns `true` if the worker's process has terminated (either -because of exiting or being signaled). Otherwise, it returns `false`. +This can only be called from the master process. -### worker.isConnected() +## cluster.isMaster -This function returns `true` if the worker is connected to its master via its IPC -channel, `false` otherwise. A worker is connected to its master after it's been -created. It is disconnected after the `disconnect` event is emitted. +* {Boolean} -### Event: 'message' +True if the process is a master. This is determined +by the `process.env.NODE_UNIQUE_ID`. If `process.env.NODE_UNIQUE_ID` is +undefined, then `isMaster` is `true`. -* `message` {Object} +## cluster.isWorker -Similar to the `cluster.on('message')` event, but specific to this worker. +* {Boolean} -This event is the same as the one provided by `child_process.fork()`. +True if the process is not a master (it is the negation of `cluster.isMaster`). -In a worker you can also use `process.on('message')`. +## cluster.schedulingPolicy -As an example, here is a cluster that keeps count of the number of requests -in the master process using the message system: +The scheduling policy, either `cluster.SCHED_RR` for round-robin or +`cluster.SCHED_NONE` to leave it to the operating system. This is a +global setting and effectively frozen once you spawn the first worker +or call `cluster.setupMaster()`, whatever comes first. - var cluster = require('cluster'); - var http = require('http'); +`SCHED_RR` is the default on all operating systems except Windows. +Windows will change to `SCHED_RR` once libuv is able to effectively +distribute IOCP handles without incurring a large performance hit. - if (cluster.isMaster) { +`cluster.schedulingPolicy` can also be set through the +`NODE_CLUSTER_SCHED_POLICY` environment variable. Valid +values are `"rr"` and `"none"`. - // Keep track of http requests - var numReqs = 0; - setInterval(function() { - console.log("numReqs =", numReqs); - }, 1000); +## cluster.settings - // Count requests - function messageHandler(msg) { - if (msg.cmd && msg.cmd == 'notifyRequest') { - numReqs += 1; - } - } +* {Object} + * `execArgv` {Array} list of string arguments passed to the Node.js + executable. (Default=`process.execArgv`) + * `exec` {String} file path to worker file. (Default=`process.argv[1]`) + * `args` {Array} string arguments passed to worker. + (Default=`process.argv.slice(2)`) + * `silent` {Boolean} whether or not to send output to parent's stdio. + (Default=`false`) + * `uid` {Number} Sets the user identity of the process. (See setuid(2).) + * `gid` {Number} Sets the group identity of the process. (See setgid(2).) - // Start workers and listen for messages containing notifyRequest - var numCPUs = require('os').cpus().length; - for (var i = 0; i < numCPUs; i++) { - cluster.fork(); - } +After calling `.setupMaster()` (or `.fork()`) this settings object will contain +the settings, including the default values. - Object.keys(cluster.workers).forEach(function(id) { - cluster.workers[id].on('message', messageHandler); - }); +It is effectively frozen after being set, because `.setupMaster()` can +only be called once. - } else { +This object is not supposed to be changed or set manually, by you. - // Worker processes have a http server. - http.Server(function(req, res) { - res.writeHead(200); - res.end("hello world\n"); +## cluster.setupMaster([settings]) - // notify master about the request - process.send({ cmd: 'notifyRequest' }); - }).listen(8000); - } +* `settings` {Object} + * `exec` {String} file path to worker file. (Default=`process.argv[1]`) + * `args` {Array} string arguments passed to worker. + (Default=`process.argv.slice(2)`) + * `silent` {Boolean} whether or not to send output to parent's stdio. + (Default=`false`) -### Event: 'online' +`setupMaster` is used to change the default 'fork' behavior. Once called, +the settings will be present in `cluster.settings`. -Similar to the `cluster.on('online')` event, but specific to this worker. +Note that: - cluster.fork().on('online', function() { - // Worker is online - }); +* any settings changes only affect future calls to `.fork()` and have no + effect on workers that are already running +* The *only* attribute of a worker that cannot be set via `.setupMaster()` is + the `env` passed to `.fork()` +* the defaults above apply to the first call only, the defaults for later + calls is the current value at the time of `cluster.setupMaster()` is called -It is not emitted in the worker. +Example: -### Event: 'listening' + var cluster = require('cluster'); + cluster.setupMaster({ + exec: 'worker.js', + args: ['--use', 'https'], + silent: true + }); + cluster.fork(); // https worker + cluster.setupMaster({ + args: ['--use', 'http'] + }); + cluster.fork(); // http worker -* `address` {Object} +This can only be called from the master process. -Similar to the `cluster.on('listening')` event, but specific to this worker. +## cluster.worker - cluster.fork().on('listening', function(address) { - // Worker is listening - }); +* {Object} -It is not emitted in the worker. +A reference to the current worker object. Not available in the master process. -### Event: 'disconnect' + var cluster = require('cluster'); -Similar to the `cluster.on('disconnect')` event, but specific to this worker. + if (cluster.isMaster) { + console.log('I am master'); + cluster.fork(); + cluster.fork(); + } else if (cluster.isWorker) { + console.log('I am worker #' + cluster.worker.id); + } - cluster.fork().on('disconnect', function() { - // Worker has disconnected - }); +## cluster.workers -### Event: 'exit' +* {Object} -* `code` {Number} the exit code, if it exited normally. -* `signal` {String} the name of the signal (eg. `'SIGHUP'`) that caused - the process to be killed. +A hash that stores the active worker objects, keyed by `id` field. Makes it +easy to loop through all the workers. It is only available in the master +process. -Similar to the `cluster.on('exit')` event, but specific to this worker. +A worker is removed from cluster.workers after the worker has disconnected _and_ +exited. The order between these two events cannot be determined in advance. +However, it is guaranteed that the removal from the cluster.workers list happens +before last `'disconnect'` or `'exit'` event is emitted. - var worker = cluster.fork(); - worker.on('exit', function(code, signal) { - if( signal ) { - console.log("worker was killed by signal: "+signal); - } else if( code !== 0 ) { - console.log("worker exited with error code: "+code); - } else { - console.log("worker success!"); + // Go through all workers + function eachWorker(callback) { + for (var id in cluster.workers) { + callback(cluster.workers[id]); } + } + eachWorker(function(worker) { + worker.send('big announcement to all workers'); }); -### Event: 'error' - -This event is the same as the one provided by `child_process.fork()`. - -In a worker you can also use `process.on('error')`. +Should you wish to reference a worker over a communication channel, using +the worker's unique id is the easiest way to find the worker. -[ChildProcess.send()]: child_process.html#child_process_child_send_message_sendhandle_callback + socket.on('data', function(id) { + var worker = cluster.workers[id]; + });