1

我有以下代码

// 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 抛出的父级错误并终止进程?

4

1 回答 1

5

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

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 });
});

更新的答案

在孩子身上

process.on('uncaughtException', (err) => {
    process.send({isError: true});
});

在主人

 master.on('message',({isError, data})=>{
    if(isError) {
         master.kill('SIGINT');
         return;
    }
    console.log('message from child', data);
    master.kill('SIGINT');
 });
于 2013-09-05T11:04:16.970 回答