如何在Node JS子进程中执行多线程 [英] How to do multithreading in node js child process

查看:148
本文介绍了如何在Node JS子进程中执行多线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个bash脚本,该bash脚本使用唯一的ID多次调用,并且我已将 socket io 用于在stdout功能上发送消息

I have a bash script that called for multiple times with unique id and I have used socket io to send messages on stdout function

shell脚本包含两个操作:

The shell script contains two actions:

  1. Action1
  2. Action2

Action2是一个后台进程,所以我不想等待脚本完成,因此当Action1完成时,我将打印回显消息(msg),该消息将在stdout函数中捕获,然后发送套接字io消息在stdout函数中

Action2 is a background process so I don't want to wait for the script completion so when the Action1 got completed then I print echo message (msg) which I will capture in the stdout function and then I sent the socket io message inside the stdout function

server.js

server.js

child_process = exec('bash some-file.sh arg1 arg2')

child_process.stdout.on('data', function) {
  if ((data).indexOf(msg) > 1) {
    io.sockets.emit('Completed for id: ' + id)
  }
});

上述代码的问题是,当我多次调用上述动作时,它对于第二次迭代不起作用(即id 1仍然存在),因为后台动作(Action2)仍在id 1的后台运行.

The problem with the above code is when I call the above action multiple times it doesn't work for second iteration (i.e id 1 still there) since the background action (Action2) is still running in the background for id 1.

如何对child_process进行多线程处理?

How to do multithreading on child_process?

推荐答案

您可以使用child_process.fork并从子进程(Actions2)发送消息

you can use child_process.fork and send the message from your subprocess (Actions2)

main.js

const child_proc = require('child_process');
const sub = child_proc.fork(`${__dirname}/sub.js`);
sub.on('message', (m) => {
  console.log('PARENT got message:', m);
});
sub.send({ from: 'server' });

sub.js

process.on('message', (m) => {
  console.log('CHILD got message:', m);
});
process.send({ from: 'client' });

这是文档 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆