如何用新的参数重新启动child_process ?



目前我正在做一个电子。js项目,我需要使用shell命令来建立与远程服务器的连续通信。为此,我生成Node的child_process并附加一个回调函数来消化接收到的数据,如下所示:

let process = child_process.spawn(“myCommand -–argument1”, [], PROCESS_OPTIONS);

process.stdout.on(“data” (data) => {
callback(data);
});

当用户通过应用程序的UI提供输入时,我必须向已经运行的进程传递一些额外的参数。为了完成这个任务,我终止了这个进程,并使用更新后的命令启动一个新进程:myCommand --argument1 --argument2

这种方法的问题是,每次我重新启动命令时,它都会在主电子进程下的任务管理器中运行2-3个僵尸进程。任务管理器截图

我是Node.js的新手,有人能建议一个更好的解决方案吗?

您可以通过stdin/stdout与子进程通信。因此,这应该在每个消息上执行代码)。例子:

//parent.js
const childProcess = require('child_process');
const child = childProcess.spawn('node', [`${__dirname}\child.js`]);
child.stdout.on('data', data => {
const msg = data.toString('utf8');
console.log('Parent got message from child:', msg);
});
child.stderr.on('data', data => {
console.log('child error:', data);
});
let itr = 0;
const intervalId = setInterval(() => {
child.stdin.write(`${itr++}`);
}, 1000);
setTimeout(() => {
clearInterval(intervalId);
child.kill(0);
process.kill(0);
}, 7000);

// child.jd
process.stdin.on('data', data => {
const msg = Number(data.toString('utf8'));
const pow2 = Math.pow(msg, 2);
process.stdout.write(`Hello from child process (got: ${msg} reply: ${pow2})`);
});

$> node parent.js
Parent got message from child: Hello from child process (got: 0 reply: 0)
Parent got message from child: Hello from child process (got: 1 reply: 1)
Parent got message from child: Hello from child process (got: 2 reply: 4)
Parent got message from child: Hello from child process (got: 3 reply: 9)
Parent got message from child: Hello from child process (got: 4 reply: 16)
Parent got message from child: Hello from child process (got: 5 reply: 25)

最新更新