-
-
Save ndelangen/3b2b981a4795e51ef4f8cf583764eb8a to your computer and use it in GitHub Desktop.
if (process.send) { | |
process.send("Hello"); | |
} | |
process.on('message', message => { | |
console.log('message from parent:', message); | |
}); |
const fork = require('child_process').fork; | |
const program = path.resolve('child.js'); | |
const parameters = []; | |
const options = { | |
stdio: [ 'pipe', 'pipe', 'pipe', 'ipc' ] | |
}; | |
const child = fork(program, parameters, options); | |
child.on('message', message => { | |
console.log('message from child:', message); | |
child.send('Hi'); | |
}); |
Each child has 1 parent, they can communicate with, A parent can spawn and communicate with any amount of children.
app.js
`const { fork } = require('child_process');
const process = require('process');
console.log('proccessID in parent:', process.pid);
const child = fork('child.js', [], {});
child.on('message', (msg) => {
console.log('The message between IPC channel, in app.js\n', msg);
});
child.send({ helloWorld: 'hello world' });
child.js
`const process = require('process');
const { fork } = require('child_process');
const child2 = fork('child2.js', [], {});
console.log('processID in child', process.pid);
process.on('message', (msg) => child2.send(msg));
child2.on('message', (msg) => process.send(msg));`
child2.js
`const process = require('process');
console.log('processID in child2 ', process.pid);
process.on('message', (msg) => {
console.log('The message between IPC channel, in child2.js:\n', msg);
});
process.send({ feedback: 'hello world' });`
result:
proccessID in parent: 61141
processID in child 61152
processID in child2 61159
The message between IPC channel, in app.js
{ feedback: 'hello world' }
The message between IPC channel, in child2.js:
{ helloWorld: 'hello world' }
How can ipc communicating with three or more file?