Last active
March 2, 2017 10:20
-
-
Save MrRaindrop/6013e6236bf79512b969 to your computer and use it in GitHub Desktop.
阿里校招在线笔试nodejs题
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
/** | |
* 实现一个nodejs的Master-Worker的小程序,要求: | |
* 1. Master维护与cpu核数相同的Worker的数量; | |
* 2. Master接收到Worker的disconnect消息时,重启新的Worker进程; | |
* 3. Worker监听1024端口并输出“Hello World”; | |
* 4. 在Worker遇到uncaughtException时,通知Master进程并等待3s后退出 | |
*/ | |
var os = require('os'), | |
cluster = require('cluster'), | |
http = require('http'), | |
cpuNum = os.cpus().length; | |
if (cluster.isMaster) { | |
for (var i = 0; i < cpuNum; i++) { | |
cluster.fork(); | |
} | |
process.on('message', function(m) { | |
console.log('message recv!'); | |
if (m.msg === 'error') { | |
console.log('error occured on worker #' + m.worker.id); | |
cluster.fork(); | |
} | |
}); | |
cluster.on('online', function(worker) { | |
console.log('worker #' + worker.id + ' is online on process #' + worker.process.pid); | |
}); | |
cluster.on('disconnect', function(worker) { | |
console.log('disconnect worker#', worker.id); | |
worker.kill(); | |
cluster.fork(); | |
}); | |
} else { | |
http.createServer(function(req, res) { | |
res.writeHead(200); | |
res.end('Hello world!'); | |
}).listen(2014); | |
cluster.worker.on('error', function(code, signal) { | |
console.log('error', process.pid, code, signal); | |
process.send({ | |
msg: 'error', | |
worker: cluster.worker | |
}); | |
setTimeout(function() { | |
cluster.worker.kill(); | |
}, 3000); | |
}); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment