使用节点js创建新进程没有pid

时间:2014-01-19 12:57:32

标签: javascript node.js

我正在关注提供的示例here 创建一个可以在多个核心上运行的服务器。我收到以下错误:

 created worker: undefined
 created worker: undefined
 created worker: undefined
 created worker: undefined

workers[m.process].lastCb=new Date().getTime();
                                 ^
TypeError: Cannot set property 'lastCb' of undefined
at Worker.<anonymous> (/home/anr/Desktop/node js/clustering2.js:56:29)
at Worker.EventEmitter.emit (events.js:98:17)
at ChildProcess.EventEmitter.emit (events.js:98:17)
at handleMessage (child_process.js:318:10)
at Pipe.channel.onread (child_process.js:345:11)

这是我的代码:

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

 var rsswarn=(50*1024*1024),
     heapWarn=(50*1024*1024);
 var workers={};

if(cluster.isMaster)
{
 for(var i=0;i<numCores;i+=1)
 {
    createWorker();
 }  

 setInterval(function killWorkers(){
    var time=new Date().getTime();
    for(pid in workers)
    {
        if(workers.hasOwnProperty(pid) && workers[pid].lastCb+5000<time)
        {
            console.log('Long running process '+pid+ ' killed');
            workers[pid].worker.kill();
            delete workers[pid];
            createWorker();
        }
    }
   },1000);
}

else
{
    http.Server(function makeServer(req,res){
if (Math.floor(Math.random() * 200) === 4) {
  console.log('Stopped ' + process.pid + ' from ever finishing');
  while(true) { continue; }
}
res.writeHead(200);
res.end('hello world from '  + process.pid + '\n');
}).listen(8000);
//Report stats once a second
setInterval(function report(){
process.send({cmd: "reportMem", memory: process.memoryUsage(), process: process.pid});
}, 1000);
}

  function createWorker()
 {
   var worker=cluster.fork();
   console.log('created worker: '+worker.pid);
   workers[worker.pid]={worker:worker,lastCb:(new Date().getTime()-1000)};
   worker.on('message',function(m){
    if(m.cmd==='reportMem')
    {
        workers[m.process].lastCb=new Date().getTime();
        if(m.memory.rss>rssWarn)
        {
            console.log('worker thread '+m.process+' taking too much memory');
        }
    }
});
}

1 个答案:

答案 0 :(得分:1)

你会在worker.process.pid中找到pid。该示例有一个拼写错误,或者对于较新版本的node.js已更改。

// This works:
console.log('created worker: ' + worker.process.pid);

参考:worker.processChildProcess.pid

将所有worker.pid更改为worker.process.pid后,您还会注意到变量rsswarn存在拼写错误,后来称为rssWarn

修好这两件事之后,你的代码就可以了。

玩得开心!