Node.js中,使用cluster創建子進程

'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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章