// Master.js let cp = require('child_process'); let os = require('os'); let cpus = os.cpus();
let net = require('net'); let server = net.createServer(); server.on('connection', function (socket) { socket.end('handle by parent!\n'); }); server.listen(8000);
// 进程自己退出时,让所有工作进程退出 process.on('exit', function (code, signal) { for (let pid of workers) workers[pid].kill(); });
for (let i = 0; i < cpus.length; i++) createWorker();
// Worker.js let http = require('http'); let server = http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('handled by child ,pid is ' + process.pid + '!\n'); });
let worker = null; process.on('message', function (m, tcp) { console.log('msg from parent', m == 'server'); if ('server' == m) worker = tcp; tcp.on('connection', function (socket) { server.emit('connection', socket); }); });
// Master.js let cp = require('child_process'); let os = require('os'); let cpus = os.cpus();
let net = require('net'); let server = net.createServer(); server.on('connection', function (socket) { socket.end('handle by parent!\n'); }); server.listen(8000);
let workers = {};
functioncreateWorker() { let child = cp.fork('./Worker.js'); child.on('message', function (message) { console.log('master message ' + message.act); if (message.act == 'suicide') createWorker(); }); child.on('exit', function (code, signal) { console.log('child ' + child.pid + ' exited'); delete workers[child.id]; });
// 进程自己退出时,让所有工作进程退出 process.on('exit', function (code, signal) { for (let pid of workers) workers[pid].kill(); });
for (let i = 0; i < cpus.length; i++) createWorker();
// Worker.js let http = require('http'); let server = http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('handled by child ,pid is ' + process.pid + '!\n'); // 模拟未捕获的异常 thrownewError('throw exception'); });
let worker = null; process.on('message', function (m, tcp) { console.log('msg from parent', m == 'server'); if ('server' == m) worker = tcp; tcp.on('connection', function (socket) { server.emit('connection', socket); }); });