Node.js 使用fork处理错误

Node.js 使用fork处理错误,node.js,fork,parent-child,child-process,Node.js,Fork,Parent Child,Child Process,在我下面的代码中,processChildOne.js抛出的Parent.js没有捕捉到错误 // Parent.js var cp = require('child_process'); var childOne = cp.fork('./processChildOne.js'); var childTwo = cp.fork('./processChildTwo.js'); childOne.on('message', function(m) { // Receive result

在我下面的代码中,processChildOne.js抛出的Parent.js没有捕捉到错误

// Parent.js

var cp = require('child_process');
var childOne = cp.fork('./processChildOne.js');
var childTwo = cp.fork('./processChildTwo.js');
childOne.on('message', function(m) {
    // Receive results from child process
    console.log('received1: ' + m);
});

// Send child process some work
childOne.send('First Fun');
childTwo.on('message', function(m) {
        // Receive results from child process
        console.log('received2: ' + m);
    });

    // Send child process some work
    childTwo.send('Second Fun');


如果processChildOne.js失败,如何向父级抛出错误,以便processChildOne.js和processChildTwo.js都应该被终止。我们如何跟踪有多少子进程已执行,还有多少子进程仍处于挂起状态。
提前谢谢


我认为发生了什么,您的子进程并没有真正抛出错误,而是写入console.error,因此父进程中没有要捕获的“错误”

node.js

var cp = require('child_process').fork('./p1.js');

cp.on('message', function(){
    console.log('error from client', arguments[0]);
})

p1.js
try{
    throw "bad stuff man"
} catch(e){
    process.send(e);
}
您可能希望在子对象中显式抛出错误,或者错误将被任何库抛出。。有了这个,我遇到了你提到的同样的问题

node.js

var cp = require('child_process').fork('./p1.js');
cp.on('message', function(){
    console.log('ya', arguments);
})

p1.js

console.error('bad stuff man')
但这至少像预期的那样抛出了错误

p1.js

throw "bad stuff man";
这用于捕获客户端中的错误并发送到父进程

node.js

var cp = require('child_process').fork('./p1.js');

cp.on('message', function(){
    console.log('error from client', arguments[0]);
})

p1.js
try{
    throw "bad stuff man"
} catch(e){
    process.send(e);
}
或者捕获客户端进程中的所有错误并将其发送给父进程

p1.js

process.on('uncaughtException', function(e){
    process.send(e);
})
throw "bad stuff man";
为了生成多个进程,并跟踪数量,您应该能够做到这一点

node.js

var numprocesses = 5, running = 0;

for(var i = numprocesses; i--;){

    var cp = require('child_process').fork('./p1.js');

    cp.on('message', function(pid){
        console.log('error from client', pid, arguments[0]);
    })

    cp.on('exit', function(){
        console.log('done'); 
        running--;
        console.log('number running', running, ', remaining', numprocesses-running);
    })

    running++;
}

p1.js

process.on('uncaughtException', function(e){
    process.send(process.pid + ': ' + e);
})

// simulate this to be a long running process of random length
setTimeout(function(){}, Math.floor(Math.random()*10000));

throw "bad stuff man";

是否可以在这里使用参数var cp=require('child_process').fork('./p1.js')调用任何函数;