|
1 | 1 | var cluster = require('cluster'); |
2 | 2 |
|
3 | | -function createWorker(i) { |
4 | | - var worker = cluster.fork(); |
5 | | - worker.on('message', function (msg) { |
6 | | - console.log('Message from worker', i, ':', msg); |
7 | | - }); |
8 | | - worker.on('disconnect', function () { |
9 | | - console.log('Worker disconnected', i); |
10 | | - }); |
11 | | - return worker; |
12 | | -} |
13 | | - |
14 | | -var workers = []; |
15 | | - |
16 | 3 | if (cluster.isMaster) { |
| 4 | + function createWorker(i) { |
| 5 | + var worker = cluster.fork(); |
| 6 | + worker.on('message', function (msg) { |
| 7 | + console.log('Message from worker' + i + ':', msg); |
| 8 | + }); |
| 9 | + worker.on('exit', function (code) { |
| 10 | + console.log(`Worker #${i} exited with code: ${code}`); |
| 11 | + }); |
| 12 | + return worker; |
| 13 | + } |
| 14 | + |
17 | 15 | for (var i = 0; i < 2; i += 1) { |
18 | 16 | console.log('Forking worker', i); |
19 | | - workers.push(createWorker(i)); |
| 17 | + createWorker(i); |
20 | 18 | } |
21 | | - process.on('SIGTERM', function () { |
| 19 | + process.once('SIGTERM', function () { |
22 | 20 | console.log('Master received SIGTERM'); |
23 | | - workers.forEach(function (worker) { |
24 | | - worker.disconnect(); |
| 21 | + cluster.disconnect(function () { |
| 22 | + console.log('All workers disconnected.'); |
25 | 23 | }); |
26 | 24 | }); |
27 | 25 | } else { |
| 26 | + var server = require('./server'); |
| 27 | + process.on('disconnect', function () { |
| 28 | + console.log(process.pid, 'disconnect received, shutting down'); |
| 29 | + if (server.lisening) { |
| 30 | + server.close(); |
| 31 | + } |
| 32 | + }); |
28 | 33 | process.send('Hello'); |
29 | | - require('./server'); |
30 | 34 | } |
0 commit comments