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
相关文章推荐
- 使用 HTTP 上传 G 级的文件之 Node.js 版本
- mongo实现消息队列
- Node.js压缩web项目中的js,css和图片
- node连接mysql数据库
- 使用 Node.js 构建交互式命令行工具
- async.js 学习记录
- 异步流程控制:7 行代码学会 co 模块
- 新时代编辑神器:Atom
- rem : web app适配的秘密武器
- jquery高级应用之Deferred对象
- ndm:NPM 的桌面 GUI 程序
- node.js中的fs.mkdir方法使用说明
- 为什么Node.js会这么火呢?Node.js流行的原因
- 究竟什么是Node.js?Node.js有什么好处?
- Linux下为Node.js程序配置MySQL或Oracle数据库的方法
- 三种Node.js写文件的方式
- node.js中的http.response.removeHeader方法使用说明
- 快速掌握Node.js模块封装及使用
- Node.js文件操作方法汇总
- Nodejs爬虫进阶教程之异步并发控制