Created
February 9, 2018 09:54
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** 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