Skip to content

Instantly share code, notes, and snippets.

@alexanderankin
Forked from jigewxy/child.js
Last active December 27, 2020 19:25
Show Gist options
  • Save alexanderankin/105af4278989f4a71036d4fd841200db to your computer and use it in GitHub Desktop.
Save alexanderankin/105af4278989f4a71036d4fd841200db to your computer and use it in GitHub Desktop.
node.js fork example --> parent/child process increment and interchange the count variable until >100
const fork = require('child_process').fork;
const child = fork(require('path').join(__dirname, 'grand-child.js'));
new Promise(r => child.once('message', r)).then(c => process.send(c));
child.on('exit', process.exit);
var count =Math.floor(Math.random()*100);
process.on('message', async (msg)=>{
console.log("CHILD: message received from parent process", msg);
count = parseInt(msg) +1;
console.log("CHILD: +1 from child");
child.send(count);
count = await new Promise(r => child.once('message', r));
if(count<=100)
process.send(count);
else
process.exit(1);
});
var count = 0;
process.on('message', (msg)=>{
console.log("GRAND-CHILD: message received from parent process", msg);
count = parseInt(msg) +1;
console.log("GRAND-CHILD: +1 from child");
if (count <= 100)
process.send(count);
else
process.exit(1);
});
console.log('gc', count);
process.send(count);
/** spawn example # spawn will not create new V8 instance, it will create a system process*/
/*
const spawn = require('child_process').spawn;
const ls = spawn("cmd", ['/c', '..']);
ls.stdout.on('data', (data)=>{
console.log(process.pid);
console.log(`stdout: ${data}`);
});
ls.stderr.on('data', (data)=>{
console.log(`stderr: ${data}`);
});
ls.on('message', (msg)=>{
console.log(`message from child process is ${msg}`);
}); */
const fork = require('child_process').fork;
const child = fork(require('path').join(__dirname, 'child.js'));
var count =0;
child.on('exit', (code) => {
console.log(`child_process exited with code ${code}`);
});
child.on('message', (msg)=>{
console.log(`PARENT: message from child process is ${msg}`);
count = parseInt(msg) + 1;
console.log("PARENT: +1 from parent");
child.send(count);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment