您的位置:首页 > Web前端 > Node.js

Node.js中,使用cluster创建子进程

2016-06-24 19:54 405 查看
'use strict';

var cluster = require('cluster');
var numCPUs = require('os').cpus().length;

// 每个fork出来的子进程, 都会从头执行该js文件
console.log('Begin to run js file. pid = ' + process.pid);

if(cluster.isMaster){
console.log('master pid = ' + process.pid);// process.pid指当前进程(主进程/子进程)的pid
for(var i = 0; i < numCPUs; i++) cluster.fork();
cluster.on('exit', (worker, code, signal)=>{
console.log('exit pid = ' + worker.process.pid);
});
//cluster.worker.process.exit(1);// 主进程cluster.worker == null
} else{
console.log('child pid = ' + process.pid);// process.pid指当前进程(主进程/子进程)的pid
if(Math.random() >= 0.5) cluster.worker.process.exit(1);// 子进程全部退出后, 主进程才会退出; 反之, 主进程不会退出
}

// outputs:
//Begin to run js file. pid = 43609
//master pid = 43609
//Begin to run js file. pid = 43614
//child pid = 43614
//Begin to run js file. pid = 43610
//child pid = 43610
//Begin to run js file. pid = 43611
//child pid = 43611
//exit pid = 43610
//Begin to run js file. pid = 43613
//child pid = 43613
//Begin to run js file. pid = 43615
//exit pid = 43613
//child pid = 43615
//Begin to run js file. pid = 43612
//child pid = 43612
//Begin to run js file. pid = 43617
//child pid = 43617
//Begin to run js file. pid = 43616
//child pid = 43616


# 命令行查看进程信息
#ps|grep node
43620 grep --color=auto --exclude-dir=.bzr --exclude-dir=CVS --exclude-dir=.git --exclude-dir=.hg --exclude-dir=.svn node
43617 /usr/local/bin/node /path/to/cluster_test.js
43616 /usr/local/bin/node /path/to/cluster_test.js
43615 /usr/local/bin/node /path/to/cluster_test.js
43614 /usr/local/bin/node /path/to/cluster_test.js
43612 /usr/local/bin/node /path/to/cluster_test.js
43611 /usr/local/bin/node /path/to/cluster_test.js
43609 node cluster_test.js
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  node.js