Main I have two files, one is the parent file and another one is the child file. I tested in two different systems one mac os monastery and another one is dell - ubuntu 20., In both systems, I'm getting the different sequences of output(console log) as in below-attached pictures
app.js:
var cp = require('child_process');
var child = cp.fork(__dirname + '/child.js');
child.on('message', function(m) {
console.log('Parent process received:', m);
});
child.send({ hello: 'from parent process' });
child.on('close', (code) => {
console.log(`child process exited with code ${code}`);
});
child.js
process.on('message', function(m) {
console.log('Child process received:', m);
});
process.send({ hello: 'from child process' });
Mac os montery: output:
Child process received: { hello: 'from parent process' }
Parent process received: { hello: 'from child process' }
Ubunt 20, output:
Parent process received: { hello: 'from child process' }
Child process received: { hello: 'from parent process' }
Output links:
When you fork a process, there are no guarantees about the order that the parent and child will next run in. Even if you see one consistent order on macOS and another on Ubuntu, this isn't guaranteed and you shouldn't rely on it. If you need things to happen in a certain order, then you need to structure your code differently to guarantee it (for example, you could have the child not send the message to the parent until it's in its own message received handler).