-
-
Save lqqyt2423/9ee8d88f9973ddd193a846c9e667fd65 to your computer and use it in GitHub Desktop.
更健壮的 master worker
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// master.js | |
'use strict'; | |
const fork = require('child_process').fork; | |
const cpus = require('os').cpus(); | |
const server = require('net').createServer(); | |
server.listen(1337); | |
const workers = {}; | |
const createWorker = function () { | |
const worker = fork('worker.js'); | |
// 启动新的进程 | |
worker.on('message', function (message) { | |
if (message.act === 'suicide') { | |
createWorker(); | |
} | |
}); | |
// 退出时重新启动新的进程 | |
worker.on('exit', function () { | |
console.log('Worker ' + worker.pid + ' exited.'); | |
delete workers[worker.pid]; | |
// createWorker(); | |
}); | |
// 句柄转发 | |
worker.send('server', server); | |
workers[worker.pid] = worker; | |
console.log('Create worker. pid: ' + worker.pid); | |
}; | |
for (let i = 0; i < cpus.length; i++) { | |
createWorker(); | |
} | |
// 进程退出前执行 | |
const exitFn = () => { | |
console.log('exit'); | |
for (const pid in workers) { | |
console.log('kill sub: ' + pid); | |
workers[pid].kill(); | |
} | |
process.exit(); | |
} | |
process.on('SIGINT', exitFn); | |
process.on('SIGTERM', exitFn); | |
// worker.js | |
'use strict'; | |
const http = require('http'); | |
const server = http.createServer(function (req, res) { | |
res.writeHead(200, { 'Content-Type': 'text/plain' }); | |
res.end('handled by child, pid is ' + process.pid + '\n'); | |
// throw new Error('throw exception'); | |
}); | |
let worker; | |
process.on('message', function (m, tcp) { | |
if (m === 'server') { | |
worker = tcp; | |
worker.on('connection', function (socket) { | |
server.emit('connection', socket); | |
}); | |
} | |
}); | |
process.on('uncaughtException', function (err) { | |
// 记录日志 | |
console.error(err); | |
// 发送自杀新号 | |
process.send({ act: 'suicide' }); | |
// 停止接收新的连接 | |
worker.close(function () { | |
// 所有已有连接断开后,退出进程 | |
process.exit(1); | |
}); | |
// 超时设置:5秒后退出进程 | |
setTimeout(function () { | |
process.exit(1); | |
}, 5000); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment