Skip to content

Commit 83963f6

Browse files
committed
Examples for 8.8
1 parent 21072f6 commit 83963f6

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

8.8/cluster.js

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
const cluster = require('cluster');
2+
const os = require('os');
3+
4+
if (cluster.isMaster) {
5+
const cpus = os.cpus().length;
6+
for (let i = 0; i<cpus; i++) {
7+
cluster.fork();
8+
}
9+
console.log(`Master PID: ${process.pid}`);
10+
11+
cluster.on('exit', (worker, code, signal) => {
12+
if (code !== 0 && !worker.exitedAfterDisconnect) {
13+
console.log(`Worker ${worker.id} crashed. ` +
14+
'Starting a new worker...');
15+
cluster.fork();
16+
}
17+
});
18+
19+
process.on('SIGUSR2', () => {
20+
const workers = Object.values(cluster.workers);
21+
22+
const restartWorker = (workerIndex) => {
23+
const worker = workers[workerIndex];
24+
if (!worker) return;
25+
26+
worker.on('exit', () => {
27+
if (!worker.exitedAfterDisconnect) return;
28+
console.log(`Exited process ${worker.process.pid}`);
29+
cluster.fork().on('listening', () => {
30+
restartWorker(workerIndex + 1);
31+
});
32+
});
33+
34+
worker.disconnect();
35+
};
36+
37+
restartWorker(0);
38+
});
39+
40+
} else {
41+
require('./server');
42+
}

8.8/server.js

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
const http = require('http');
2+
const pid = process.pid;
3+
4+
http.createServer((req, res) => {
5+
for (let i=0; i<1e7; i++); // simulate CPU work
6+
res.end(`Handled by process ${pid}`);
7+
}).listen(8080, () => {
8+
console.log(`Started process ${pid}`);
9+
});
10+
11+
// setTimeout(() => {
12+
// process.exit(1) // death by random timeout
13+
// }, Math.random() * 10000);

0 commit comments

Comments
 (0)