使用Fork向child发送错误给父级

时间:2013-09-05 10:47:44

标签: node.js fork fork-join

我有以下代码

// Parent.js

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

child.on('message', function(m) {
    // Receive results from child process
    console.log('received: ' + m);
});

// Send child process some work
child.send('First Fun');
// pChild.js

process.on('message', function(m) {
console.log("Helloooooooooo from pChild.js")
// Pass results back to parent process
process.send("Fun1 complete");
});

如何处理从pChild.js抛出的父级错误并终止进程?

1 个答案:

答案 0 :(得分:4)

子进程中未处理的错误将导致它退出,这将在child对象上发出'exit' event

child.on('exit', function (code, signal) {
    console.log('Child exited:', code, signal);
});

如果在孩子中处理错误,可以将其作为另一条消息发送:

// in pChild.js
/* ... */.on('error', function (error) {
    process.send({ error: error.message || error });
});