cluster.html 27.7 KB
Newer Older
1 2 3 4
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
5
  <title>Cluster Node.js v0.10.17 Manual &amp; Documentation</title>
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
  <link rel="stylesheet" href="assets/style.css">
  <link rel="stylesheet" href="assets/sh.css">
  <link rel="canonical" href="http://nodejs.org/api/cluster.html">
</head>
<body class="alt apidoc" id="api-section-cluster">
    <div id="intro" class="interior">
        <a href="/" title="Go back to the home page">
            <img id="logo" src="http://nodejs.org/images/logo-light.png" alt="node.js">
        </a>
    </div>
    <div id="content" class="clearfix">
        <div id="column2" class="interior">
            <ul>
                <li><a href="/" class="home">Home</a></li>
                <li><a href="/download/" class="download">Download</a></li>
                <li><a href="/about/" class="about">About</a></li>
22
                <li><a href="http://npmjs.org/" class="npm">npm Registry</a></li>
23 24 25 26 27 28 29 30 31 32 33
                <li><a href="http://nodejs.org/api/" class="docs current">Docs</a></li>
                <li><a href="http://blog.nodejs.org" class="blog">Blog</a></li>
                <li><a href="/community/" class="community">Community</a></li>
                <li><a href="/logos/" class="logos">Logos</a></li>
                <li><a href="http://jobs.nodejs.org/" class="jobs">Jobs</a></li>
            </ul>
            <p class="twitter"><a href="http://twitter.com/nodejs">@nodejs</a></p>
        </div>

        <div id="column1" class="interior">
          <header>
34
            <h1>Node.js v0.10.17 Manual &amp; Documentation</h1>
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
            <div id="gtoc">
              <p>
                <a href="index.html" name="toc">Index</a> |
                <a href="all.html">View on single page</a> |
                <a href="cluster.json">View as JSON</a>
              </p>
            </div>
            <hr>
          </header>

          <div id="toc">
            <h2>Table of Contents</h2>
            <ul>
<li><a href="#cluster_cluster">Cluster</a><ul>
<li><a href="#cluster_how_it_works">How It Works</a></li>
<li><a href="#cluster_cluster_settings">cluster.settings</a></li>
<li><a href="#cluster_cluster_ismaster">cluster.isMaster</a></li>
<li><a href="#cluster_cluster_isworker">cluster.isWorker</a></li>
<li><a href="#cluster_event_fork">Event: &#39;fork&#39;</a></li>
<li><a href="#cluster_event_online">Event: &#39;online&#39;</a></li>
<li><a href="#cluster_event_listening">Event: &#39;listening&#39;</a></li>
<li><a href="#cluster_event_disconnect">Event: &#39;disconnect&#39;</a></li>
<li><a href="#cluster_event_exit">Event: &#39;exit&#39;</a></li>
<li><a href="#cluster_event_setup">Event: &#39;setup&#39;</a></li>
<li><a href="#cluster_cluster_setupmaster_settings">cluster.setupMaster([settings])</a></li>
<li><a href="#cluster_cluster_fork_env">cluster.fork([env])</a></li>
<li><a href="#cluster_cluster_disconnect_callback">cluster.disconnect([callback])</a></li>
<li><a href="#cluster_cluster_worker">cluster.worker</a></li>
<li><a href="#cluster_cluster_workers">cluster.workers</a></li>
<li><a href="#cluster_class_worker">Class: Worker</a><ul>
<li><a href="#cluster_worker_id">worker.id</a></li>
<li><a href="#cluster_worker_process">worker.process</a></li>
<li><a href="#cluster_worker_suicide">worker.suicide</a></li>
<li><a href="#cluster_worker_send_message_sendhandle">worker.send(message, [sendHandle])</a></li>
69
<li><a href="#cluster_worker_kill_signal_sigterm">worker.kill([signal=&#39;SIGTERM&#39;])</a></li>
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
<li><a href="#cluster_worker_disconnect">worker.disconnect()</a></li>
<li><a href="#cluster_event_message">Event: &#39;message&#39;</a></li>
<li><a href="#cluster_event_online_1">Event: &#39;online&#39;</a></li>
<li><a href="#cluster_event_listening_1">Event: &#39;listening&#39;</a></li>
<li><a href="#cluster_event_disconnect_1">Event: &#39;disconnect&#39;</a></li>
<li><a href="#cluster_event_exit_1">Event: &#39;exit&#39;</a></li>
</ul>
</li>
</ul>
</li>
</ul>

          </div>

          <div id="apicontent">
            <h1>Cluster<span><a class="mark" href="#cluster_cluster" id="cluster_cluster">#</a></span></h1>
86
<pre class="api_stability_1">Stability: 1 - Experimental</pre><p>A single instance of Node runs in a single thread. To take advantage of
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
multi-core systems the user will sometimes want to launch a cluster of Node
processes to handle the load.

</p>
<p>The cluster module allows you to easily create a network of processes that
all share server ports.

</p>
<pre><code>var cluster = require(&#39;cluster&#39;);
var http = require(&#39;http&#39;);
var numCPUs = require(&#39;os&#39;).cpus().length;

if (cluster.isMaster) {
  // Fork workers.
  for (var i = 0; i &lt; numCPUs; i++) {
    cluster.fork();
  }

  cluster.on(&#39;exit&#39;, function(worker, code, signal) {
    console.log(&#39;worker &#39; + worker.process.pid + &#39; died&#39;);
  });
} else {
  // Workers can share any TCP connection
  // In this case its a HTTP server
  http.createServer(function(req, res) {
    res.writeHead(200);
    res.end(&quot;hello world\n&quot;);
  }).listen(8000);
}</code></pre>
<p>Running node will now share port 8000 between the workers:

</p>
119 120 121 122 123
<pre><code>% NODE_DEBUG=cluster node server.js
23521,Master Worker 23524 online
23521,Master Worker 23526 online
23521,Master Worker 23523 online
23521,Master Worker 23528 online</code></pre>
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
<p>This feature was introduced recently, and may change in future versions.
Please try it out and provide feedback.

</p>
<p>Also note that, on Windows, it is not yet possible to set up a named pipe
server in a worker.

</p>
<h2>How It Works<span><a class="mark" href="#cluster_how_it_works" id="cluster_how_it_works">#</a></span></h2>
<!--type=misc-->

<p>The worker processes are spawned using the <code>child_process.fork</code> method,
so that they can communicate with the parent via IPC and pass server
handles back and forth.

</p>
<p>When you call <code>server.listen(...)</code> in a worker, it serializes the
arguments and passes the request to the master process.  If the master
process already has a listening server matching the worker&#39;s
requirements, then it passes the handle to the worker.  If it does not
already have a listening server matching that requirement, then it will
create one, and pass the handle to the child.

</p>
<p>This causes potentially surprising behavior in three edge cases:

</p>
<ol>
<li><code>server.listen({fd: 7})</code> Because the message is passed to the master,
file descriptor 7 <strong>in the parent</strong> will be listened on, and the
handle passed to the worker, rather than listening to the worker&#39;s
idea of what the number 7 file descriptor references.</li>
<li><code>server.listen(handle)</code> Listening on handles explicitly will cause
the worker to use the supplied handle, rather than talk to the master
process.  If the worker already has the handle, then it&#39;s presumed
that you know what you are doing.</li>
<li><code>server.listen(0)</code> Normally, this will cause servers to listen on a
random port.  However, in a cluster, each worker will receive the
same &quot;random&quot; port each time they do <code>listen(0)</code>.  In essence, the
port is random the first time, but predictable thereafter.  If you
want to listen on a unique port, generate a port number based on the
cluster worker ID.</li>
</ol>
<p>When multiple processes are all <code>accept()</code>ing on the same underlying
resource, the operating system load-balances across them very
efficiently.  There is no routing logic in Node.js, or in your program,
and no shared state between the workers.  Therefore, it is important to
design your program such that it does not rely too heavily on in-memory
data objects for things like sessions and login.

</p>
<p>Because workers are all separate processes, they can be killed or
re-spawned depending on your program&#39;s needs, without affecting other
workers.  As long as there are some workers still alive, the server will
continue to accept connections.  Node does not automatically manage the
number of workers for you, however.  It is your responsibility to manage
the worker pool for your application&#39;s needs.

</p>
<h2>cluster.settings<span><a class="mark" href="#cluster_cluster_settings" id="cluster_cluster_settings">#</a></span></h2>
<div class="signature"><ul>
<li><span class="type">Object</span><ul>
<li><code>exec</code> <span class="type">String</span> file path to worker file.  (Default=<code>__filename</code>)</li>
<li><code>args</code> <span class="type">Array</span> string arguments passed to worker.
(Default=<code>process.argv.slice(2)</code>)</li>
<li><code>silent</code> <span class="type">Boolean</span> whether or not to send output to parent&#39;s stdio.
(Default=<code>false</code>)</li>
</ul>
</li>
</div></ul>
<p>All settings set by the <code>.setupMaster</code> is stored in this settings object.
195
This object is not supposed to be changed or set manually, by you.
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275

</p>
<h2>cluster.isMaster<span><a class="mark" href="#cluster_cluster_ismaster" id="cluster_cluster_ismaster">#</a></span></h2>
<div class="signature"><ul>
<li><span class="type">Boolean</span></li>
</div></ul>
<p>True if the process is a master. This is determined
by the <code>process.env.NODE_UNIQUE_ID</code>. If <code>process.env.NODE_UNIQUE_ID</code> is
undefined, then <code>isMaster</code> is <code>true</code>.

</p>
<h2>cluster.isWorker<span><a class="mark" href="#cluster_cluster_isworker" id="cluster_cluster_isworker">#</a></span></h2>
<div class="signature"><ul>
<li><span class="type">Boolean</span></li>
</div></ul>
<p>This boolean flag is true if the process is a worker forked from a master.
If the <code>process.env.NODE_UNIQUE_ID</code> is set to a value, then
<code>isWorker</code> is <code>true</code>.

</p>
<h2>Event: &#39;fork&#39;<span><a class="mark" href="#cluster_event_fork" id="cluster_event_fork">#</a></span></h2>
<div class="signature"><ul>
<li><code>worker</code> <span class="type">Worker object</span></li>
</div></ul>
<p>When a new worker is forked the cluster module will emit a &#39;fork&#39; event.
This can be used to log worker activity, and create you own timeout.

</p>
<pre><code>var timeouts = [];
function errorMsg() {
  console.error(&quot;Something must be wrong with the connection ...&quot;);
}

cluster.on(&#39;fork&#39;, function(worker) {
  timeouts[worker.id] = setTimeout(errorMsg, 2000);
});
cluster.on(&#39;listening&#39;, function(worker, address) {
  clearTimeout(timeouts[worker.id]);
});
cluster.on(&#39;exit&#39;, function(worker, code, signal) {
  clearTimeout(timeouts[worker.id]);
  errorMsg();
});</code></pre>
<h2>Event: &#39;online&#39;<span><a class="mark" href="#cluster_event_online" id="cluster_event_online">#</a></span></h2>
<div class="signature"><ul>
<li><code>worker</code> <span class="type">Worker object</span></li>
</div></ul>
<p>After forking a new worker, the worker should respond with a online message.
When the master receives a online message it will emit such event.
The difference between &#39;fork&#39; and &#39;online&#39; is that fork is emitted when the
master tries to fork a worker, and &#39;online&#39; is emitted when the worker is
being executed.

</p>
<pre><code>cluster.on(&#39;online&#39;, function(worker) {
  console.log(&quot;Yay, the worker responded after it was forked&quot;);
});</code></pre>
<h2>Event: &#39;listening&#39;<span><a class="mark" href="#cluster_event_listening" id="cluster_event_listening">#</a></span></h2>
<div class="signature"><ul>
<li><code>worker</code> <span class="type">Worker object</span></li>
<li><code>address</code> <span class="type">Object</span></li>
</div></ul>
<p>When calling <code>listen()</code> from a worker, a &#39;listening&#39; event is automatically assigned
to the server instance. When the server is listening a message is send to the master
where the &#39;listening&#39; event is emitted.

</p>
<p>The event handler is executed with two arguments, the <code>worker</code> contains the worker
object and the <code>address</code> object contains the following connection properties:
<code>address</code>, <code>port</code> and <code>addressType</code>. This is very useful if the worker is listening
on more than one address.

</p>
<pre><code>cluster.on(&#39;listening&#39;, function(worker, address) {
  console.log(&quot;A worker is now connected to &quot; + address.address + &quot;:&quot; + address.port);
});</code></pre>
<h2>Event: &#39;disconnect&#39;<span><a class="mark" href="#cluster_event_disconnect" id="cluster_event_disconnect">#</a></span></h2>
<div class="signature"><ul>
<li><code>worker</code> <span class="type">Worker object</span></li>
</div></ul>
276 277 278
<p>When a workers IPC channel has disconnected this event is emitted.
This will happen when the worker dies, usually after calling
<code>.kill()</code>.
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433

</p>
<p>When calling <code>.disconnect()</code>, there may be a delay between the
<code>disconnect</code> and <code>exit</code> events.  This event can be used to detect if
the process is stuck in a cleanup or if there are long-living
connections.

</p>
<pre><code>cluster.on(&#39;disconnect&#39;, function(worker) {
  console.log(&#39;The worker #&#39; + worker.id + &#39; has disconnected&#39;);
});</code></pre>
<h2>Event: &#39;exit&#39;<span><a class="mark" href="#cluster_event_exit" id="cluster_event_exit">#</a></span></h2>
<div class="signature"><ul>
<li><code>worker</code> <span class="type">Worker object</span></li>
<li><code>code</code> <span class="type">Number</span> the exit code, if it exited normally.</li>
<li><code>signal</code> <span class="type">String</span> the name of the signal (eg. <code>&#39;SIGHUP&#39;</code>) that caused
the process to be killed.</li>
</div></ul>
<p>When any of the workers die the cluster module will emit the &#39;exit&#39; event.
This can be used to restart the worker by calling <code>fork()</code> again.

</p>
<pre><code>cluster.on(&#39;exit&#39;, function(worker, code, signal) {
  var exitCode = worker.process.exitCode;
  console.log(&#39;worker &#39; + worker.process.pid + &#39; died (&#39;+exitCode+&#39;). restarting...&#39;);
  cluster.fork();
});</code></pre>
<h2>Event: &#39;setup&#39;<span><a class="mark" href="#cluster_event_setup" id="cluster_event_setup">#</a></span></h2>
<div class="signature"><ul>
<li><code>worker</code> <span class="type">Worker object</span></li>
</div></ul>
<p>When the <code>.setupMaster()</code> function has been executed this event emits.
If <code>.setupMaster()</code> was not executed before <code>fork()</code> this function will
call <code>.setupMaster()</code> with no arguments.

</p>
<h2>cluster.setupMaster([settings])<span><a class="mark" href="#cluster_cluster_setupmaster_settings" id="cluster_cluster_setupmaster_settings">#</a></span></h2>
<div class="signature"><ul>
<li><code>settings</code> <span class="type">Object</span><ul>
<li><code>exec</code> <span class="type">String</span> file path to worker file.  (Default=<code>__filename</code>)</li>
<li><code>args</code> <span class="type">Array</span> string arguments passed to worker.
(Default=<code>process.argv.slice(2)</code>)</li>
<li><code>silent</code> <span class="type">Boolean</span> whether or not to send output to parent&#39;s stdio.
(Default=<code>false</code>)</li>
</ul>
</li>
</div></ul>
<p><code>setupMaster</code> is used to change the default &#39;fork&#39; behavior. The new settings
are effective immediately and permanently, they cannot be changed later on.

</p>
<p>Example:

</p>
<pre><code>var cluster = require(&quot;cluster&quot;);
cluster.setupMaster({
  exec : &quot;worker.js&quot;,
  args : [&quot;--use&quot;, &quot;https&quot;],
  silent : true
});
cluster.fork();</code></pre>
<h2>cluster.fork([env])<span><a class="mark" href="#cluster_cluster_fork_env" id="cluster_cluster_fork_env">#</a></span></h2>
<div class="signature"><ul>
<li><code>env</code> <span class="type">Object</span> Key/value pairs to add to child process environment.</li>
<li>return <span class="type">Worker object</span></li>
</div></ul>
<p>Spawn a new worker process. This can only be called from the master process.

</p>
<h2>cluster.disconnect([callback])<span><a class="mark" href="#cluster_cluster_disconnect_callback" id="cluster_cluster_disconnect_callback">#</a></span></h2>
<div class="signature"><ul>
<li><code>callback</code> <span class="type">Function</span> called when all workers are disconnected and handlers are closed</li>
</div></ul>
<p>When calling this method, all workers will commit a graceful suicide. When they are
disconnected all internal handlers will be closed, allowing the master process to
die graceful if no other event is waiting.

</p>
<p>The method takes an optional callback argument which will be called when finished.

</p>
<h2>cluster.worker<span><a class="mark" href="#cluster_cluster_worker" id="cluster_cluster_worker">#</a></span></h2>
<div class="signature"><ul>
<li><span class="type">Object</span></li>
</div></ul>
<p>A reference to the current worker object. Not available in the master process.

</p>
<pre><code>var cluster = require(&#39;cluster&#39;);

if (cluster.isMaster) {
  console.log(&#39;I am master&#39;);
  cluster.fork();
  cluster.fork();
} else if (cluster.isWorker) {
  console.log(&#39;I am worker #&#39; + cluster.worker.id);
}</code></pre>
<h2>cluster.workers<span><a class="mark" href="#cluster_cluster_workers" id="cluster_cluster_workers">#</a></span></h2>
<div class="signature"><ul>
<li><span class="type">Object</span></li>
</div></ul>
<p>A hash that stores the active worker objects, keyed by <code>id</code> field. Makes it
easy to loop through all the workers. It is only available in the master
process.

</p>
<pre><code>// Go through all workers
function eachWorker(callback) {
  for (var id in cluster.workers) {
    callback(cluster.workers[id]);
  }
}
eachWorker(function(worker) {
  worker.send(&#39;big announcement to all workers&#39;);
});</code></pre>
<p>Should you wish to reference a worker over a communication channel, using
the worker&#39;s unique id is the easiest way to find the worker.

</p>
<pre><code>socket.on(&#39;data&#39;, function(id) {
  var worker = cluster.workers[id];
});</code></pre>
<h2>Class: Worker<span><a class="mark" href="#cluster_class_worker" id="cluster_class_worker">#</a></span></h2>
<p>A Worker object contains all public information and method about a worker.
In the master it can be obtained using <code>cluster.workers</code>. In a worker
it can be obtained using <code>cluster.worker</code>.

</p>
<h3>worker.id<span><a class="mark" href="#cluster_worker_id" id="cluster_worker_id">#</a></span></h3>
<div class="signature"><ul>
<li><span class="type">String</span></li>
</div></ul>
<p>Each new worker is given its own unique id, this id is stored in the
<code>id</code>.

</p>
<p>While a worker is alive, this is the key that indexes it in
cluster.workers

</p>
<h3>worker.process<span><a class="mark" href="#cluster_worker_process" id="cluster_worker_process">#</a></span></h3>
<div class="signature"><ul>
<li><span class="type">ChildProcess object</span></li>
</div></ul>
<p>All workers are created using <code>child_process.fork()</code>, the returned object
from this function is stored in process.

</p>
<p>See: <a href="child_process.html">Child Process module</a>

</p>
<h3>worker.suicide<span><a class="mark" href="#cluster_worker_suicide" id="cluster_worker_suicide">#</a></span></h3>
<div class="signature"><ul>
<li><span class="type">Boolean</span></li>
</div></ul>
434 435 436
<p>This property is a boolean. It is set when a worker dies after calling
<code>.kill()</code> or immediately after calling the <code>.disconnect()</code> method.
Until then it is <code>undefined</code>.
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461

</p>
<h3>worker.send(message, [sendHandle])<span><a class="mark" href="#cluster_worker_send_message_sendhandle" id="cluster_worker_send_message_sendhandle">#</a></span></h3>
<div class="signature"><ul>
<li><code>message</code> <span class="type">Object</span></li>
<li><code>sendHandle</code> <span class="type">Handle object</span></li>
</div></ul>
<p>This function is equal to the send methods provided by
<code>child_process.fork()</code>.  In the master you should use this function to
send a message to a specific worker.  However in a worker you can also use
<code>process.send(message)</code>, since this is the same function.

</p>
<p>This example will echo back all messages from the master:

</p>
<pre><code>if (cluster.isMaster) {
  var worker = cluster.fork();
  worker.send(&#39;hi there&#39;);

} else if (cluster.isWorker) {
  process.on(&#39;message&#39;, function(msg) {
    process.send(msg);
  });
}</code></pre>
462 463 464 465 466
<h3>worker.kill([signal=&#39;SIGTERM&#39;])<span><a class="mark" href="#cluster_worker_kill_signal_sigterm" id="cluster_worker_kill_signal_sigterm">#</a></span></h3>
<div class="signature"><ul>
<li><code>signal</code> <span class="type">String</span> Name of the kill signal to send to the worker
process.</li>
</div></ul>
467 468 469 470 471 472 473 474 475 476 477
<p>This function will kill the worker, and inform the master to not spawn a
new worker.  The boolean <code>suicide</code> lets you distinguish between voluntary
and accidental exit.

</p>
<pre><code>cluster.on(&#39;exit&#39;, function(worker, code, signal) {
  if (worker.suicide === true) {
    console.log(&#39;Oh, it was just suicide\&#39; – no need to worry&#39;).
  }
});

478 479 480 481 482 483
// kill worker
worker.kill();</code></pre>
<p>This method is aliased as <code>worker.destroy()</code> for backwards
compatibility.

</p>
484 485 486 487 488 489 490 491 492 493 494
<h3>worker.disconnect()<span><a class="mark" href="#cluster_worker_disconnect" id="cluster_worker_disconnect">#</a></span></h3>
<p>When calling this function the worker will no longer accept new connections, but
they will be handled by any other listening worker. Existing connection will be
allowed to exit as usual. When no more connections exist, the IPC channel to the worker
will close allowing it to die graceful. When the IPC channel is closed the <code>disconnect</code>
event will emit, this is then followed by the <code>exit</code> event, there is emitted when
the worker finally die.

</p>
<p>Because there might be long living connections, it is useful to implement a timeout.
This example ask the worker to disconnect and after 2 seconds it will destroy the
495
server. An alternative would be to execute <code>worker.kill()</code> after 2 seconds, but
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
that would normally not allow the worker to do any cleanup if needed.

</p>
<pre><code>if (cluster.isMaster) {
  var worker = cluster.fork();
  var timeout;

  worker.on(&#39;listening&#39;, function(address) {
    worker.disconnect();
    timeout = setTimeout(function() {
      worker.send(&#39;force kill&#39;);
    }, 2000);
  });

  worker.on(&#39;disconnect&#39;, function() {
    clearTimeout(timeout);
  });

} else if (cluster.isWorker) {
  var net = require(&#39;net&#39;);
  var server = net.createServer(function(socket) {
    // connection never end
  });

  server.listen(8000);

  server.on(&#39;close&#39;, function() {
    // cleanup
  });

  process.on(&#39;message&#39;, function(msg) {
    if (msg === &#39;force kill&#39;) {
528
      server.close();
529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
    }
  });
}</code></pre>
<h3>Event: &#39;message&#39;<span><a class="mark" href="#cluster_event_message" id="cluster_event_message">#</a></span></h3>
<div class="signature"><ul>
<li><code>message</code> <span class="type">Object</span></li>
</div></ul>
<p>This event is the same as the one provided by <code>child_process.fork()</code>.
In the master you should use this event, however in a worker you can also use
<code>process.on(&#39;message&#39;)</code>

</p>
<p>As an example, here is a cluster that keeps count of the number of requests
in the master process using the message system:

</p>
<pre><code>var cluster = require(&#39;cluster&#39;);
var http = require(&#39;http&#39;);

if (cluster.isMaster) {

  // Keep track of http requests
  var numReqs = 0;
  setInterval(function() {
    console.log(&quot;numReqs =&quot;, numReqs);
  }, 1000);

  // Count requestes
  function messageHandler(msg) {
    if (msg.cmd &amp;&amp; msg.cmd == &#39;notifyRequest&#39;) {
      numReqs += 1;
    }
  }

  // Start workers and listen for messages containing notifyRequest
  var numCPUs = require(&#39;os&#39;).cpus().length;
  for (var i = 0; i &lt; numCPUs; i++) {
    cluster.fork();
  }

  Object.keys(cluster.workers).forEach(function(id) {
    cluster.workers[id].on(&#39;message&#39;, messageHandler);
  });

} else {

  // Worker processes have a http server.
  http.Server(function(req, res) {
    res.writeHead(200);
    res.end(&quot;hello world\n&quot;);

    // notify master about the request
    process.send({ cmd: &#39;notifyRequest&#39; });
  }).listen(8000);
}</code></pre>
<h3>Event: &#39;online&#39;<span><a class="mark" href="#cluster_event_online_1" id="cluster_event_online_1">#</a></span></h3>
<p>Same as the <code>cluster.on(&#39;online&#39;)</code> event, but emits only when the state change
on the specified worker.

</p>
<pre><code>cluster.fork().on(&#39;online&#39;, function() {
  // Worker is online
591
});</code></pre>
592 593 594 595 596 597 598 599 600 601
<h3>Event: &#39;listening&#39;<span><a class="mark" href="#cluster_event_listening_1" id="cluster_event_listening_1">#</a></span></h3>
<div class="signature"><ul>
<li><code>address</code> <span class="type">Object</span></li>
</div></ul>
<p>Same as the <code>cluster.on(&#39;listening&#39;)</code> event, but emits only when the state change
on the specified worker.

</p>
<pre><code>cluster.fork().on(&#39;listening&#39;, function(address) {
  // Worker is listening
602
});</code></pre>
603 604 605 606 607 608 609
<h3>Event: &#39;disconnect&#39;<span><a class="mark" href="#cluster_event_disconnect_1" id="cluster_event_disconnect_1">#</a></span></h3>
<p>Same as the <code>cluster.on(&#39;disconnect&#39;)</code> event, but emits only when the state change
on the specified worker.

</p>
<pre><code>cluster.fork().on(&#39;disconnect&#39;, function() {
  // Worker has disconnected
610
});</code></pre>
611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629
<h3>Event: &#39;exit&#39;<span><a class="mark" href="#cluster_event_exit_1" id="cluster_event_exit_1">#</a></span></h3>
<div class="signature"><ul>
<li><code>code</code> <span class="type">Number</span> the exit code, if it exited normally.</li>
<li><code>signal</code> <span class="type">String</span> the name of the signal (eg. <code>&#39;SIGHUP&#39;</code>) that caused
the process to be killed.</li>
</div></ul>
<p>Emitted by the individual worker instance, when the underlying child process
is terminated.  See <a href="child_process.html#child_process_event_exit">child_process event: &#39;exit&#39;</a>.

</p>
<pre><code>var worker = cluster.fork();
worker.on(&#39;exit&#39;, function(code, signal) {
  if( signal ) {
    console.log(&quot;worker was killed by signal: &quot;+signal);
  } else if( code !== 0 ) {
    console.log(&quot;worker exited with error code: &quot;+code);
  } else {
    console.log(&quot;worker success!&quot;);
  }
630
});</code></pre>
631 632 633 634 635

          </div>
        </div>
    </div>
    <div id="footer">
636
        <a href="http://joyent.com" class="joyent-logo">Joyent</a>
637 638 639 640
        <ul class="clearfix">
            <li><a href="/">Node.js</a></li>
            <li><a href="/download/">Download</a></li>
            <li><a href="/about/">About</a></li>
641
            <li><a href="http://npmjs.org/">npm Registry</a></li>
642 643 644 645 646 647 648 649
            <li><a href="http://nodejs.org/api/">Docs</a></li>
            <li><a href="http://blog.nodejs.org">Blog</a></li>
            <li><a href="/community/">Community</a></li>
            <li><a href="/logos/">Logos</a></li>
            <li><a href="http://jobs.nodejs.org/">Jobs</a></li>
            <li><a href="http://twitter.com/nodejs" class="twitter">@nodejs</a></li>
        </ul>

650
        <p>Copyright <a href="http://joyent.com/">Joyent, Inc</a>, Node.js is a <a href="/trademark-policy.pdf">trademark</a> of Joyent, Inc. View <a href="https://raw.github.com/joyent/node/v0.10.17/LICENSE">license</a>.</p>
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
    </div>

  <script src="../sh_main.js"></script>
  <script src="../sh_javascript.min.js"></script>
  <script>highlight(undefined, undefined, 'pre');</script>
  <script>
    window._gaq = [['_setAccount', 'UA-10874194-2'], ['_trackPageview']];
    (function(d, t) {
      var g = d.createElement(t),
          s = d.getElementsByTagName(t)[0];
      g.src = '//www.google-analytics.com/ga.js';
      s.parentNode.insertBefore(g, s);
    }(document, 'script'));
  </script>
</body>
</html>