Skip to content

Instantly share code, notes, and snippets.

@jigewxy
Created February 9, 2018 09:54
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jigewxy/97a75e86cc616cebf1160280297547a6 to your computer and use it in GitHub Desktop.
Save jigewxy/97a75e86cc616cebf1160280297547a6 to your computer and use it in GitHub Desktop.
node.js fork example --> parent/child process increment and interchange the count variable until >100
var count =Math.floor(Math.random()*100);
process.on('message', (msg)=>{
console.log("CHILD: message received from parent process", msg);
count = parseInt(msg) +1;
console.log("CHILD: +1 from child");
if(count<=100)
process.send(count);
else
process.exit(1);
});
console.log(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 ls = fork("../child/child.js");
var count =0;
ls.on('exit', (code)=>{
console.log(`child_process exited with code ${code}`);
});
ls.on('message', (msg)=>{
console.log(`PARENT: message from child process is ${msg}`);
count = parseInt(msg) + 1;
console.log("PARENT: +1 from parent");
ls.send(count);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment