问题描述
child_process 使用for()方法创建子进程后,子进程可以正常接收父进程发送的消息,但在父进程中无法获取子进程发送的消息是什么原因?
问题出现的环境背景及自己尝试过哪些方法
Node.Js版本 v10.16.3
相关代码
父进程代码
const { fork } = require('child_process');
const path = require('path');
router.post('/rollingrow', async (ctx, next) => {
let { filePath, modelName } = ctx.request.body;
let cp = fork(path.join(__dirname, '../../work-process/rollingrow.js'), [], {
cwd: process.cwd(),
env: process.env, //子进程的环境变量
execPath: process.execPath, //运行模块的可执行文件
execArgv: process.execArgv, //传递给可执行文件的参数列表
silent: false, //为false表示父进程与子进程共享标准(输入/输出),为true时不共享。
});
// 这里无法获取子进程发送的消息
cp.on('message', (data) => {
console.log(`got a message is ${data}`, JSON.stringify(data));
});
// 这里无法获取子进程发送错误时的错误信息
cp.on('error', function (err) {
console.log(err.message);
});
// 父进程传递给子进程的消息,子进程可正常接收
cp.send({ filePath, modelName });
});
子进程代码
let { ThomasService } = require('../services/thomas');
const errors = require('../../core/http-exception');
process.on('message', async (msg) => {
console.log('子进程收到消息', msg);
global.errs = errors;
// 由父进程发送的消息可正常接收
let filePath = msg.filePath;
let modelName = msg.modelName;
try {
let result = await new ThomasService({
originalname: filePath,
modelName: modelName,
}).rollingRow();
} catch (error) {
// 捕获错误后,向父进程发送消息,父进程中无法获取到
process.send(`${error.message}`);
process.kill(process.pid, 'SIGTERM');
}
});
// 执行完成后,向父进程发送消息,父进程中无法获取到
process.send({ msg: 'done' });
你期待的结果是什么?实际看到的错误信息又是什么?
期待的结果是子进程执行的js文件正常完成以后往父进程传递成功消息,或者子进程执发生错误的时候往父进程传递失败的消息。父进程接收后根据子进程传递的成功/失败消息进行下一步处理。目前实际的情况是子进程可以接收父进程发送的消息,但父进程无法接收子进程的消息。