问题
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
The shell script contains two actions:
- Action1
- Action2
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
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)
}
});
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.
How to do multithreading on child_process?
回答1:
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' });
Here are the document and a good article explained it
来源:https://stackoverflow.com/questions/52057838/how-to-do-multithreading-in-node-js-child-process