Skip to content

Instantly share code, notes, and snippets.

@jigewxy
Created February 9, 2018 09:54
Show Gist options
  • Select an option

  • Save jigewxy/97a75e86cc616cebf1160280297547a6 to your computer and use it in GitHub Desktop.

Select an option

Save jigewxy/97a75e86cc616cebf1160280297547a6 to your computer and use it in GitHub Desktop.

Revisions

  1. jigewxy created this gist Feb 9, 2018.
    19 changes: 19 additions & 0 deletions child.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,19 @@

    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);
    52 changes: 52 additions & 0 deletions index.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,52 @@


    /** 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);

    });