~yolanda.robla/ubuntu/trusty/nodejs/add_distribution

« back to all changes in this revision

Viewing changes to doc/api/cluster.html

  • Committer: Package Import Robot
  • Author(s): Jérémy Lal
  • Date: 2013-08-14 00:16:46 UTC
  • mfrom: (7.1.40 sid)
  • Revision ID: package-import@ubuntu.com-20130814001646-bzlysfh8sd6mukbo
Tags: 0.10.15~dfsg1-4
* Update 2005 patch, adding a handful of tests that can fail on
  slow platforms.
* Add 1004 patch to fix test failures when writing NaN to buffer
  on mipsel.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
<!doctype html>
 
2
<html lang="en">
 
3
<head>
 
4
  <meta charset="utf-8">
 
5
  <title>Cluster Node.js v0.10.15 Manual &amp; Documentation</title>
 
6
  <link rel="stylesheet" href="assets/style.css">
 
7
  <link rel="stylesheet" href="assets/sh.css">
 
8
  <link rel="canonical" href="http://nodejs.org/api/cluster.html">
 
9
</head>
 
10
<body class="alt apidoc" id="api-section-cluster">
 
11
    <div id="intro" class="interior">
 
12
        <a href="/" title="Go back to the home page">
 
13
            <img id="logo" src="http://nodejs.org/images/logo-light.png" alt="node.js">
 
14
        </a>
 
15
    </div>
 
16
    <div id="content" class="clearfix">
 
17
        <div id="column2" class="interior">
 
18
            <ul>
 
19
                <li><a href="/" class="home">Home</a></li>
 
20
                <li><a href="/download/" class="download">Download</a></li>
 
21
                <li><a href="/about/" class="about">About</a></li>
 
22
                <li><a href="http://npmjs.org/" class="npm">npm Registry</a></li>
 
23
                <li><a href="http://nodejs.org/api/" class="docs current">Docs</a></li>
 
24
                <li><a href="http://blog.nodejs.org" class="blog">Blog</a></li>
 
25
                <li><a href="/community/" class="community">Community</a></li>
 
26
                <li><a href="/logos/" class="logos">Logos</a></li>
 
27
                <li><a href="http://jobs.nodejs.org/" class="jobs">Jobs</a></li>
 
28
            </ul>
 
29
            <p class="twitter"><a href="http://twitter.com/nodejs">@nodejs</a></p>
 
30
        </div>
 
31
 
 
32
        <div id="column1" class="interior">
 
33
          <header>
 
34
            <h1>Node.js v0.10.15 Manual &amp; Documentation</h1>
 
35
            <div id="gtoc">
 
36
              <p>
 
37
                <a href="index.html" name="toc">Index</a> |
 
38
                <a href="all.html">View on single page</a> |
 
39
                <a href="cluster.json">View as JSON</a>
 
40
              </p>
 
41
            </div>
 
42
            <hr>
 
43
          </header>
 
44
 
 
45
          <div id="toc">
 
46
            <h2>Table of Contents</h2>
 
47
            <ul>
 
48
<li><a href="#cluster_cluster">Cluster</a><ul>
 
49
<li><a href="#cluster_how_it_works">How It Works</a></li>
 
50
<li><a href="#cluster_cluster_settings">cluster.settings</a></li>
 
51
<li><a href="#cluster_cluster_ismaster">cluster.isMaster</a></li>
 
52
<li><a href="#cluster_cluster_isworker">cluster.isWorker</a></li>
 
53
<li><a href="#cluster_event_fork">Event: &#39;fork&#39;</a></li>
 
54
<li><a href="#cluster_event_online">Event: &#39;online&#39;</a></li>
 
55
<li><a href="#cluster_event_listening">Event: &#39;listening&#39;</a></li>
 
56
<li><a href="#cluster_event_disconnect">Event: &#39;disconnect&#39;</a></li>
 
57
<li><a href="#cluster_event_exit">Event: &#39;exit&#39;</a></li>
 
58
<li><a href="#cluster_event_setup">Event: &#39;setup&#39;</a></li>
 
59
<li><a href="#cluster_cluster_setupmaster_settings">cluster.setupMaster([settings])</a></li>
 
60
<li><a href="#cluster_cluster_fork_env">cluster.fork([env])</a></li>
 
61
<li><a href="#cluster_cluster_disconnect_callback">cluster.disconnect([callback])</a></li>
 
62
<li><a href="#cluster_cluster_worker">cluster.worker</a></li>
 
63
<li><a href="#cluster_cluster_workers">cluster.workers</a></li>
 
64
<li><a href="#cluster_class_worker">Class: Worker</a><ul>
 
65
<li><a href="#cluster_worker_id">worker.id</a></li>
 
66
<li><a href="#cluster_worker_process">worker.process</a></li>
 
67
<li><a href="#cluster_worker_suicide">worker.suicide</a></li>
 
68
<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
<li><a href="#cluster_worker_disconnect">worker.disconnect()</a></li>
 
71
<li><a href="#cluster_event_message">Event: &#39;message&#39;</a></li>
 
72
<li><a href="#cluster_event_online_1">Event: &#39;online&#39;</a></li>
 
73
<li><a href="#cluster_event_listening_1">Event: &#39;listening&#39;</a></li>
 
74
<li><a href="#cluster_event_disconnect_1">Event: &#39;disconnect&#39;</a></li>
 
75
<li><a href="#cluster_event_exit_1">Event: &#39;exit&#39;</a></li>
 
76
</ul>
 
77
</li>
 
78
</ul>
 
79
</li>
 
80
</ul>
 
81
 
 
82
          </div>
 
83
 
 
84
          <div id="apicontent">
 
85
            <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
multi-core systems the user will sometimes want to launch a cluster of Node
 
88
processes to handle the load.
 
89
 
 
90
</p>
 
91
<p>The cluster module allows you to easily create a network of processes that
 
92
all share server ports.
 
93
 
 
94
</p>
 
95
<pre><code>var cluster = require(&#39;cluster&#39;);
 
96
var http = require(&#39;http&#39;);
 
97
var numCPUs = require(&#39;os&#39;).cpus().length;
 
98
 
 
99
if (cluster.isMaster) {
 
100
  // Fork workers.
 
101
  for (var i = 0; i &lt; numCPUs; i++) {
 
102
    cluster.fork();
 
103
  }
 
104
 
 
105
  cluster.on(&#39;exit&#39;, function(worker, code, signal) {
 
106
    console.log(&#39;worker &#39; + worker.process.pid + &#39; died&#39;);
 
107
  });
 
108
} else {
 
109
  // Workers can share any TCP connection
 
110
  // In this case its a HTTP server
 
111
  http.createServer(function(req, res) {
 
112
    res.writeHead(200);
 
113
    res.end(&quot;hello world\n&quot;);
 
114
  }).listen(8000);
 
115
}</code></pre>
 
116
<p>Running node will now share port 8000 between the workers:
 
117
 
 
118
</p>
 
119
<pre><code>% NODE_DEBUG=cluster node server.js
 
120
23521,Master Worker 23524 online
 
121
23521,Master Worker 23526 online
 
122
23521,Master Worker 23523 online
 
123
23521,Master Worker 23528 online</code></pre>
 
124
<p>This feature was introduced recently, and may change in future versions.
 
125
Please try it out and provide feedback.
 
126
 
 
127
</p>
 
128
<p>Also note that, on Windows, it is not yet possible to set up a named pipe
 
129
server in a worker.
 
130
 
 
131
</p>
 
132
<h2>How It Works<span><a class="mark" href="#cluster_how_it_works" id="cluster_how_it_works">#</a></span></h2>
 
133
<!--type=misc-->
 
134
 
 
135
<p>The worker processes are spawned using the <code>child_process.fork</code> method,
 
136
so that they can communicate with the parent via IPC and pass server
 
137
handles back and forth.
 
138
 
 
139
</p>
 
140
<p>When you call <code>server.listen(...)</code> in a worker, it serializes the
 
141
arguments and passes the request to the master process.  If the master
 
142
process already has a listening server matching the worker&#39;s
 
143
requirements, then it passes the handle to the worker.  If it does not
 
144
already have a listening server matching that requirement, then it will
 
145
create one, and pass the handle to the child.
 
146
 
 
147
</p>
 
148
<p>This causes potentially surprising behavior in three edge cases:
 
149
 
 
150
</p>
 
151
<ol>
 
152
<li><code>server.listen({fd: 7})</code> Because the message is passed to the master,
 
153
file descriptor 7 <strong>in the parent</strong> will be listened on, and the
 
154
handle passed to the worker, rather than listening to the worker&#39;s
 
155
idea of what the number 7 file descriptor references.</li>
 
156
<li><code>server.listen(handle)</code> Listening on handles explicitly will cause
 
157
the worker to use the supplied handle, rather than talk to the master
 
158
process.  If the worker already has the handle, then it&#39;s presumed
 
159
that you know what you are doing.</li>
 
160
<li><code>server.listen(0)</code> Normally, this will cause servers to listen on a
 
161
random port.  However, in a cluster, each worker will receive the
 
162
same &quot;random&quot; port each time they do <code>listen(0)</code>.  In essence, the
 
163
port is random the first time, but predictable thereafter.  If you
 
164
want to listen on a unique port, generate a port number based on the
 
165
cluster worker ID.</li>
 
166
</ol>
 
167
<p>When multiple processes are all <code>accept()</code>ing on the same underlying
 
168
resource, the operating system load-balances across them very
 
169
efficiently.  There is no routing logic in Node.js, or in your program,
 
170
and no shared state between the workers.  Therefore, it is important to
 
171
design your program such that it does not rely too heavily on in-memory
 
172
data objects for things like sessions and login.
 
173
 
 
174
</p>
 
175
<p>Because workers are all separate processes, they can be killed or
 
176
re-spawned depending on your program&#39;s needs, without affecting other
 
177
workers.  As long as there are some workers still alive, the server will
 
178
continue to accept connections.  Node does not automatically manage the
 
179
number of workers for you, however.  It is your responsibility to manage
 
180
the worker pool for your application&#39;s needs.
 
181
 
 
182
</p>
 
183
<h2>cluster.settings<span><a class="mark" href="#cluster_cluster_settings" id="cluster_cluster_settings">#</a></span></h2>
 
184
<div class="signature"><ul>
 
185
<li><span class="type">Object</span><ul>
 
186
<li><code>exec</code> <span class="type">String</span> file path to worker file.  (Default=<code>__filename</code>)</li>
 
187
<li><code>args</code> <span class="type">Array</span> string arguments passed to worker.
 
188
(Default=<code>process.argv.slice(2)</code>)</li>
 
189
<li><code>silent</code> <span class="type">Boolean</span> whether or not to send output to parent&#39;s stdio.
 
190
(Default=<code>false</code>)</li>
 
191
</ul>
 
192
</li>
 
193
</div></ul>
 
194
<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
</p>
 
198
<h2>cluster.isMaster<span><a class="mark" href="#cluster_cluster_ismaster" id="cluster_cluster_ismaster">#</a></span></h2>
 
199
<div class="signature"><ul>
 
200
<li><span class="type">Boolean</span></li>
 
201
</div></ul>
 
202
<p>True if the process is a master. This is determined
 
203
by the <code>process.env.NODE_UNIQUE_ID</code>. If <code>process.env.NODE_UNIQUE_ID</code> is
 
204
undefined, then <code>isMaster</code> is <code>true</code>.
 
205
 
 
206
</p>
 
207
<h2>cluster.isWorker<span><a class="mark" href="#cluster_cluster_isworker" id="cluster_cluster_isworker">#</a></span></h2>
 
208
<div class="signature"><ul>
 
209
<li><span class="type">Boolean</span></li>
 
210
</div></ul>
 
211
<p>This boolean flag is true if the process is a worker forked from a master.
 
212
If the <code>process.env.NODE_UNIQUE_ID</code> is set to a value, then
 
213
<code>isWorker</code> is <code>true</code>.
 
214
 
 
215
</p>
 
216
<h2>Event: &#39;fork&#39;<span><a class="mark" href="#cluster_event_fork" id="cluster_event_fork">#</a></span></h2>
 
217
<div class="signature"><ul>
 
218
<li><code>worker</code> <span class="type">Worker object</span></li>
 
219
</div></ul>
 
220
<p>When a new worker is forked the cluster module will emit a &#39;fork&#39; event.
 
221
This can be used to log worker activity, and create you own timeout.
 
222
 
 
223
</p>
 
224
<pre><code>var timeouts = [];
 
225
function errorMsg() {
 
226
  console.error(&quot;Something must be wrong with the connection ...&quot;);
 
227
}
 
228
 
 
229
cluster.on(&#39;fork&#39;, function(worker) {
 
230
  timeouts[worker.id] = setTimeout(errorMsg, 2000);
 
231
});
 
232
cluster.on(&#39;listening&#39;, function(worker, address) {
 
233
  clearTimeout(timeouts[worker.id]);
 
234
});
 
235
cluster.on(&#39;exit&#39;, function(worker, code, signal) {
 
236
  clearTimeout(timeouts[worker.id]);
 
237
  errorMsg();
 
238
});</code></pre>
 
239
<h2>Event: &#39;online&#39;<span><a class="mark" href="#cluster_event_online" id="cluster_event_online">#</a></span></h2>
 
240
<div class="signature"><ul>
 
241
<li><code>worker</code> <span class="type">Worker object</span></li>
 
242
</div></ul>
 
243
<p>After forking a new worker, the worker should respond with a online message.
 
244
When the master receives a online message it will emit such event.
 
245
The difference between &#39;fork&#39; and &#39;online&#39; is that fork is emitted when the
 
246
master tries to fork a worker, and &#39;online&#39; is emitted when the worker is
 
247
being executed.
 
248
 
 
249
</p>
 
250
<pre><code>cluster.on(&#39;online&#39;, function(worker) {
 
251
  console.log(&quot;Yay, the worker responded after it was forked&quot;);
 
252
});</code></pre>
 
253
<h2>Event: &#39;listening&#39;<span><a class="mark" href="#cluster_event_listening" id="cluster_event_listening">#</a></span></h2>
 
254
<div class="signature"><ul>
 
255
<li><code>worker</code> <span class="type">Worker object</span></li>
 
256
<li><code>address</code> <span class="type">Object</span></li>
 
257
</div></ul>
 
258
<p>When calling <code>listen()</code> from a worker, a &#39;listening&#39; event is automatically assigned
 
259
to the server instance. When the server is listening a message is send to the master
 
260
where the &#39;listening&#39; event is emitted.
 
261
 
 
262
</p>
 
263
<p>The event handler is executed with two arguments, the <code>worker</code> contains the worker
 
264
object and the <code>address</code> object contains the following connection properties:
 
265
<code>address</code>, <code>port</code> and <code>addressType</code>. This is very useful if the worker is listening
 
266
on more than one address.
 
267
 
 
268
</p>
 
269
<pre><code>cluster.on(&#39;listening&#39;, function(worker, address) {
 
270
  console.log(&quot;A worker is now connected to &quot; + address.address + &quot;:&quot; + address.port);
 
271
});</code></pre>
 
272
<h2>Event: &#39;disconnect&#39;<span><a class="mark" href="#cluster_event_disconnect" id="cluster_event_disconnect">#</a></span></h2>
 
273
<div class="signature"><ul>
 
274
<li><code>worker</code> <span class="type">Worker object</span></li>
 
275
</div></ul>
 
276
<p>When a workers IPC channel has disconnected this event is emitted.
 
277
This will happen when the worker dies, usually after calling
 
278
<code>.kill()</code>.
 
279
 
 
280
</p>
 
281
<p>When calling <code>.disconnect()</code>, there may be a delay between the
 
282
<code>disconnect</code> and <code>exit</code> events.  This event can be used to detect if
 
283
the process is stuck in a cleanup or if there are long-living
 
284
connections.
 
285
 
 
286
</p>
 
287
<pre><code>cluster.on(&#39;disconnect&#39;, function(worker) {
 
288
  console.log(&#39;The worker #&#39; + worker.id + &#39; has disconnected&#39;);
 
289
});</code></pre>
 
290
<h2>Event: &#39;exit&#39;<span><a class="mark" href="#cluster_event_exit" id="cluster_event_exit">#</a></span></h2>
 
291
<div class="signature"><ul>
 
292
<li><code>worker</code> <span class="type">Worker object</span></li>
 
293
<li><code>code</code> <span class="type">Number</span> the exit code, if it exited normally.</li>
 
294
<li><code>signal</code> <span class="type">String</span> the name of the signal (eg. <code>&#39;SIGHUP&#39;</code>) that caused
 
295
the process to be killed.</li>
 
296
</div></ul>
 
297
<p>When any of the workers die the cluster module will emit the &#39;exit&#39; event.
 
298
This can be used to restart the worker by calling <code>fork()</code> again.
 
299
 
 
300
</p>
 
301
<pre><code>cluster.on(&#39;exit&#39;, function(worker, code, signal) {
 
302
  var exitCode = worker.process.exitCode;
 
303
  console.log(&#39;worker &#39; + worker.process.pid + &#39; died (&#39;+exitCode+&#39;). restarting...&#39;);
 
304
  cluster.fork();
 
305
});</code></pre>
 
306
<h2>Event: &#39;setup&#39;<span><a class="mark" href="#cluster_event_setup" id="cluster_event_setup">#</a></span></h2>
 
307
<div class="signature"><ul>
 
308
<li><code>worker</code> <span class="type">Worker object</span></li>
 
309
</div></ul>
 
310
<p>When the <code>.setupMaster()</code> function has been executed this event emits.
 
311
If <code>.setupMaster()</code> was not executed before <code>fork()</code> this function will
 
312
call <code>.setupMaster()</code> with no arguments.
 
313
 
 
314
</p>
 
315
<h2>cluster.setupMaster([settings])<span><a class="mark" href="#cluster_cluster_setupmaster_settings" id="cluster_cluster_setupmaster_settings">#</a></span></h2>
 
316
<div class="signature"><ul>
 
317
<li><code>settings</code> <span class="type">Object</span><ul>
 
318
<li><code>exec</code> <span class="type">String</span> file path to worker file.  (Default=<code>__filename</code>)</li>
 
319
<li><code>args</code> <span class="type">Array</span> string arguments passed to worker.
 
320
(Default=<code>process.argv.slice(2)</code>)</li>
 
321
<li><code>silent</code> <span class="type">Boolean</span> whether or not to send output to parent&#39;s stdio.
 
322
(Default=<code>false</code>)</li>
 
323
</ul>
 
324
</li>
 
325
</div></ul>
 
326
<p><code>setupMaster</code> is used to change the default &#39;fork&#39; behavior. The new settings
 
327
are effective immediately and permanently, they cannot be changed later on.
 
328
 
 
329
</p>
 
330
<p>Example:
 
331
 
 
332
</p>
 
333
<pre><code>var cluster = require(&quot;cluster&quot;);
 
334
cluster.setupMaster({
 
335
  exec : &quot;worker.js&quot;,
 
336
  args : [&quot;--use&quot;, &quot;https&quot;],
 
337
  silent : true
 
338
});
 
339
cluster.fork();</code></pre>
 
340
<h2>cluster.fork([env])<span><a class="mark" href="#cluster_cluster_fork_env" id="cluster_cluster_fork_env">#</a></span></h2>
 
341
<div class="signature"><ul>
 
342
<li><code>env</code> <span class="type">Object</span> Key/value pairs to add to child process environment.</li>
 
343
<li>return <span class="type">Worker object</span></li>
 
344
</div></ul>
 
345
<p>Spawn a new worker process. This can only be called from the master process.
 
346
 
 
347
</p>
 
348
<h2>cluster.disconnect([callback])<span><a class="mark" href="#cluster_cluster_disconnect_callback" id="cluster_cluster_disconnect_callback">#</a></span></h2>
 
349
<div class="signature"><ul>
 
350
<li><code>callback</code> <span class="type">Function</span> called when all workers are disconnected and handlers are closed</li>
 
351
</div></ul>
 
352
<p>When calling this method, all workers will commit a graceful suicide. When they are
 
353
disconnected all internal handlers will be closed, allowing the master process to
 
354
die graceful if no other event is waiting.
 
355
 
 
356
</p>
 
357
<p>The method takes an optional callback argument which will be called when finished.
 
358
 
 
359
</p>
 
360
<h2>cluster.worker<span><a class="mark" href="#cluster_cluster_worker" id="cluster_cluster_worker">#</a></span></h2>
 
361
<div class="signature"><ul>
 
362
<li><span class="type">Object</span></li>
 
363
</div></ul>
 
364
<p>A reference to the current worker object. Not available in the master process.
 
365
 
 
366
</p>
 
367
<pre><code>var cluster = require(&#39;cluster&#39;);
 
368
 
 
369
if (cluster.isMaster) {
 
370
  console.log(&#39;I am master&#39;);
 
371
  cluster.fork();
 
372
  cluster.fork();
 
373
} else if (cluster.isWorker) {
 
374
  console.log(&#39;I am worker #&#39; + cluster.worker.id);
 
375
}</code></pre>
 
376
<h2>cluster.workers<span><a class="mark" href="#cluster_cluster_workers" id="cluster_cluster_workers">#</a></span></h2>
 
377
<div class="signature"><ul>
 
378
<li><span class="type">Object</span></li>
 
379
</div></ul>
 
380
<p>A hash that stores the active worker objects, keyed by <code>id</code> field. Makes it
 
381
easy to loop through all the workers. It is only available in the master
 
382
process.
 
383
 
 
384
</p>
 
385
<pre><code>// Go through all workers
 
386
function eachWorker(callback) {
 
387
  for (var id in cluster.workers) {
 
388
    callback(cluster.workers[id]);
 
389
  }
 
390
}
 
391
eachWorker(function(worker) {
 
392
  worker.send(&#39;big announcement to all workers&#39;);
 
393
});</code></pre>
 
394
<p>Should you wish to reference a worker over a communication channel, using
 
395
the worker&#39;s unique id is the easiest way to find the worker.
 
396
 
 
397
</p>
 
398
<pre><code>socket.on(&#39;data&#39;, function(id) {
 
399
  var worker = cluster.workers[id];
 
400
});</code></pre>
 
401
<h2>Class: Worker<span><a class="mark" href="#cluster_class_worker" id="cluster_class_worker">#</a></span></h2>
 
402
<p>A Worker object contains all public information and method about a worker.
 
403
In the master it can be obtained using <code>cluster.workers</code>. In a worker
 
404
it can be obtained using <code>cluster.worker</code>.
 
405
 
 
406
</p>
 
407
<h3>worker.id<span><a class="mark" href="#cluster_worker_id" id="cluster_worker_id">#</a></span></h3>
 
408
<div class="signature"><ul>
 
409
<li><span class="type">String</span></li>
 
410
</div></ul>
 
411
<p>Each new worker is given its own unique id, this id is stored in the
 
412
<code>id</code>.
 
413
 
 
414
</p>
 
415
<p>While a worker is alive, this is the key that indexes it in
 
416
cluster.workers
 
417
 
 
418
</p>
 
419
<h3>worker.process<span><a class="mark" href="#cluster_worker_process" id="cluster_worker_process">#</a></span></h3>
 
420
<div class="signature"><ul>
 
421
<li><span class="type">ChildProcess object</span></li>
 
422
</div></ul>
 
423
<p>All workers are created using <code>child_process.fork()</code>, the returned object
 
424
from this function is stored in process.
 
425
 
 
426
</p>
 
427
<p>See: <a href="child_process.html">Child Process module</a>
 
428
 
 
429
</p>
 
430
<h3>worker.suicide<span><a class="mark" href="#cluster_worker_suicide" id="cluster_worker_suicide">#</a></span></h3>
 
431
<div class="signature"><ul>
 
432
<li><span class="type">Boolean</span></li>
 
433
</div></ul>
 
434
<p>This property is a boolean. It is set when a worker dies after calling
 
435
<code>.kill()</code> or immediately after calling the <code>.disconnect()</code> method.
 
436
Until then it is <code>undefined</code>.
 
437
 
 
438
</p>
 
439
<h3>worker.send(message, [sendHandle])<span><a class="mark" href="#cluster_worker_send_message_sendhandle" id="cluster_worker_send_message_sendhandle">#</a></span></h3>
 
440
<div class="signature"><ul>
 
441
<li><code>message</code> <span class="type">Object</span></li>
 
442
<li><code>sendHandle</code> <span class="type">Handle object</span></li>
 
443
</div></ul>
 
444
<p>This function is equal to the send methods provided by
 
445
<code>child_process.fork()</code>.  In the master you should use this function to
 
446
send a message to a specific worker.  However in a worker you can also use
 
447
<code>process.send(message)</code>, since this is the same function.
 
448
 
 
449
</p>
 
450
<p>This example will echo back all messages from the master:
 
451
 
 
452
</p>
 
453
<pre><code>if (cluster.isMaster) {
 
454
  var worker = cluster.fork();
 
455
  worker.send(&#39;hi there&#39;);
 
456
 
 
457
} else if (cluster.isWorker) {
 
458
  process.on(&#39;message&#39;, function(msg) {
 
459
    process.send(msg);
 
460
  });
 
461
}</code></pre>
 
462
<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>
 
463
<div class="signature"><ul>
 
464
<li><code>signal</code> <span class="type">String</span> Name of the kill signal to send to the worker
 
465
process.</li>
 
466
</div></ul>
 
467
<p>This function will kill the worker, and inform the master to not spawn a
 
468
new worker.  The boolean <code>suicide</code> lets you distinguish between voluntary
 
469
and accidental exit.
 
470
 
 
471
</p>
 
472
<pre><code>cluster.on(&#39;exit&#39;, function(worker, code, signal) {
 
473
  if (worker.suicide === true) {
 
474
    console.log(&#39;Oh, it was just suicide\&#39; – no need to worry&#39;).
 
475
  }
 
476
});
 
477
 
 
478
// kill worker
 
479
worker.kill();</code></pre>
 
480
<p>This method is aliased as <code>worker.destroy()</code> for backwards
 
481
compatibility.
 
482
 
 
483
</p>
 
484
<h3>worker.disconnect()<span><a class="mark" href="#cluster_worker_disconnect" id="cluster_worker_disconnect">#</a></span></h3>
 
485
<p>When calling this function the worker will no longer accept new connections, but
 
486
they will be handled by any other listening worker. Existing connection will be
 
487
allowed to exit as usual. When no more connections exist, the IPC channel to the worker
 
488
will close allowing it to die graceful. When the IPC channel is closed the <code>disconnect</code>
 
489
event will emit, this is then followed by the <code>exit</code> event, there is emitted when
 
490
the worker finally die.
 
491
 
 
492
</p>
 
493
<p>Because there might be long living connections, it is useful to implement a timeout.
 
494
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
that would normally not allow the worker to do any cleanup if needed.
 
497
 
 
498
</p>
 
499
<pre><code>if (cluster.isMaster) {
 
500
  var worker = cluster.fork();
 
501
  var timeout;
 
502
 
 
503
  worker.on(&#39;listening&#39;, function(address) {
 
504
    worker.disconnect();
 
505
    timeout = setTimeout(function() {
 
506
      worker.send(&#39;force kill&#39;);
 
507
    }, 2000);
 
508
  });
 
509
 
 
510
  worker.on(&#39;disconnect&#39;, function() {
 
511
    clearTimeout(timeout);
 
512
  });
 
513
 
 
514
} else if (cluster.isWorker) {
 
515
  var net = require(&#39;net&#39;);
 
516
  var server = net.createServer(function(socket) {
 
517
    // connection never end
 
518
  });
 
519
 
 
520
  server.listen(8000);
 
521
 
 
522
  server.on(&#39;close&#39;, function() {
 
523
    // cleanup
 
524
  });
 
525
 
 
526
  process.on(&#39;message&#39;, function(msg) {
 
527
    if (msg === &#39;force kill&#39;) {
 
528
      server.close();
 
529
    }
 
530
  });
 
531
}</code></pre>
 
532
<h3>Event: &#39;message&#39;<span><a class="mark" href="#cluster_event_message" id="cluster_event_message">#</a></span></h3>
 
533
<div class="signature"><ul>
 
534
<li><code>message</code> <span class="type">Object</span></li>
 
535
</div></ul>
 
536
<p>This event is the same as the one provided by <code>child_process.fork()</code>.
 
537
In the master you should use this event, however in a worker you can also use
 
538
<code>process.on(&#39;message&#39;)</code>
 
539
 
 
540
</p>
 
541
<p>As an example, here is a cluster that keeps count of the number of requests
 
542
in the master process using the message system:
 
543
 
 
544
</p>
 
545
<pre><code>var cluster = require(&#39;cluster&#39;);
 
546
var http = require(&#39;http&#39;);
 
547
 
 
548
if (cluster.isMaster) {
 
549
 
 
550
  // Keep track of http requests
 
551
  var numReqs = 0;
 
552
  setInterval(function() {
 
553
    console.log(&quot;numReqs =&quot;, numReqs);
 
554
  }, 1000);
 
555
 
 
556
  // Count requestes
 
557
  function messageHandler(msg) {
 
558
    if (msg.cmd &amp;&amp; msg.cmd == &#39;notifyRequest&#39;) {
 
559
      numReqs += 1;
 
560
    }
 
561
  }
 
562
 
 
563
  // Start workers and listen for messages containing notifyRequest
 
564
  var numCPUs = require(&#39;os&#39;).cpus().length;
 
565
  for (var i = 0; i &lt; numCPUs; i++) {
 
566
    cluster.fork();
 
567
  }
 
568
 
 
569
  Object.keys(cluster.workers).forEach(function(id) {
 
570
    cluster.workers[id].on(&#39;message&#39;, messageHandler);
 
571
  });
 
572
 
 
573
} else {
 
574
 
 
575
  // Worker processes have a http server.
 
576
  http.Server(function(req, res) {
 
577
    res.writeHead(200);
 
578
    res.end(&quot;hello world\n&quot;);
 
579
 
 
580
    // notify master about the request
 
581
    process.send({ cmd: &#39;notifyRequest&#39; });
 
582
  }).listen(8000);
 
583
}</code></pre>
 
584
<h3>Event: &#39;online&#39;<span><a class="mark" href="#cluster_event_online_1" id="cluster_event_online_1">#</a></span></h3>
 
585
<p>Same as the <code>cluster.on(&#39;online&#39;)</code> event, but emits only when the state change
 
586
on the specified worker.
 
587
 
 
588
</p>
 
589
<pre><code>cluster.fork().on(&#39;online&#39;, function() {
 
590
  // Worker is online
 
591
});</code></pre>
 
592
<h3>Event: &#39;listening&#39;<span><a class="mark" href="#cluster_event_listening_1" id="cluster_event_listening_1">#</a></span></h3>
 
593
<div class="signature"><ul>
 
594
<li><code>address</code> <span class="type">Object</span></li>
 
595
</div></ul>
 
596
<p>Same as the <code>cluster.on(&#39;listening&#39;)</code> event, but emits only when the state change
 
597
on the specified worker.
 
598
 
 
599
</p>
 
600
<pre><code>cluster.fork().on(&#39;listening&#39;, function(address) {
 
601
  // Worker is listening
 
602
});</code></pre>
 
603
<h3>Event: &#39;disconnect&#39;<span><a class="mark" href="#cluster_event_disconnect_1" id="cluster_event_disconnect_1">#</a></span></h3>
 
604
<p>Same as the <code>cluster.on(&#39;disconnect&#39;)</code> event, but emits only when the state change
 
605
on the specified worker.
 
606
 
 
607
</p>
 
608
<pre><code>cluster.fork().on(&#39;disconnect&#39;, function() {
 
609
  // Worker has disconnected
 
610
});</code></pre>
 
611
<h3>Event: &#39;exit&#39;<span><a class="mark" href="#cluster_event_exit_1" id="cluster_event_exit_1">#</a></span></h3>
 
612
<div class="signature"><ul>
 
613
<li><code>code</code> <span class="type">Number</span> the exit code, if it exited normally.</li>
 
614
<li><code>signal</code> <span class="type">String</span> the name of the signal (eg. <code>&#39;SIGHUP&#39;</code>) that caused
 
615
the process to be killed.</li>
 
616
</div></ul>
 
617
<p>Emitted by the individual worker instance, when the underlying child process
 
618
is terminated.  See <a href="child_process.html#child_process_event_exit">child_process event: &#39;exit&#39;</a>.
 
619
 
 
620
</p>
 
621
<pre><code>var worker = cluster.fork();
 
622
worker.on(&#39;exit&#39;, function(code, signal) {
 
623
  if( signal ) {
 
624
    console.log(&quot;worker was killed by signal: &quot;+signal);
 
625
  } else if( code !== 0 ) {
 
626
    console.log(&quot;worker exited with error code: &quot;+code);
 
627
  } else {
 
628
    console.log(&quot;worker success!&quot;);
 
629
  }
 
630
});</code></pre>
 
631
 
 
632
          </div>
 
633
        </div>
 
634
    </div>
 
635
    <div id="footer">
 
636
        <a href="http://joyent.com" class="joyent-logo">Joyent</a>
 
637
        <ul class="clearfix">
 
638
            <li><a href="/">Node.js</a></li>
 
639
            <li><a href="/download/">Download</a></li>
 
640
            <li><a href="/about/">About</a></li>
 
641
            <li><a href="http://npmjs.org/">npm Registry</a></li>
 
642
            <li><a href="http://nodejs.org/api/">Docs</a></li>
 
643
            <li><a href="http://blog.nodejs.org">Blog</a></li>
 
644
            <li><a href="/community/">Community</a></li>
 
645
            <li><a href="/logos/">Logos</a></li>
 
646
            <li><a href="http://jobs.nodejs.org/">Jobs</a></li>
 
647
            <li><a href="http://twitter.com/nodejs" class="twitter">@nodejs</a></li>
 
648
        </ul>
 
649
 
 
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.15/LICENSE">license</a>.</p>
 
651
    </div>
 
652
 
 
653
  <script src="../sh_main.js"></script>
 
654
  <script src="../sh_javascript.min.js"></script>
 
655
  <script>highlight(undefined, undefined, 'pre');</script>
 
656
  <script>
 
657
    window._gaq = [['_setAccount', 'UA-10874194-2'], ['_trackPageview']];
 
658
    (function(d, t) {
 
659
      var g = d.createElement(t),
 
660
          s = d.getElementsByTagName(t)[0];
 
661
      g.src = '//www.google-analytics.com/ga.js';
 
662
      s.parentNode.insertBefore(g, s);
 
663
    }(document, 'script'));
 
664
  </script>
 
665
</body>
 
666
</html>
 
667