目前,我正在处理一个Electron.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新手,有人能为这个场景提出更好的解决方案吗?
发布于 2022-02-12 00:26:35
您可以通过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)https://stackoverflow.com/questions/69134720
复制相似问题