1

在我下面的代码中,错误没有被 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

process.on('message', function(m) {
var conn = mongoose.createConnection('mongodb://localhost:27017/DB');

conn.on('error', console.error.bind(console, 'connection error:'));
// Pass results back to parent process
process.send("Fun1 complete");
});


如果 processChildOne.js 失败,如何向父级抛出错误,以便 processChildOne.js 和 processChildTwo.js 都应该被杀死。我们如何跟踪已经执行了多少子进程以及仍有多少子进程处于待处理状态。
提前致谢

4

1 回答 1

4

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

您可能想明确地在孩子中抛出一个错误,或者任何库都会抛出一个错误..有了这个,我遇到了你提到的同样的问题..

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";
于 2013-09-06T16:39:07.763 回答