node.js - Getting the correct process id from child processes -


so, i'm spawning few processes , trying figure out pid of process when gets data, here's code:

var mod_child_process = require('child_process'); var mod_events        = require('events');  (var i=0; i<3; ++i) {     var childprocess;      childprocess = mod_child_process.spawn('handshake.exe', ['n:192.168.200.250:3001:1', 'q:time']);          childprocess.stdout.on('data', function(data) {              console.log('stdout (' + childprocess.pid + '): ' + data);     });  } 

it returns single pid

stdout (78748): 18/7/13 15:46:26 stdout (78748): 18/7/13 15:46:26 stdout (78748): 18/7/13 15:46:27 

thanks in advance.

you're running scoping issue variable childprocess. variables in javascript function scoped. because of this, variable isn't exclusive loop.

simplified example of code acting how have it:

for (var = 0; < 3; ++i) {     var somenumber = i;      settimeout(function() {         console.log(somenumber);     }, 100); } 

outputs: 2, 2, 2

and fix:

for (var = 0; < 3; ++i) {     (function() {         var somenumber = i;          settimeout(function() {             console.log(somenumber);         }, 100);     })(); } 

you want wrap logic in closure variable childprocess exists scope. above code outputs expected 0, 1, 2


Comments

Popular posts from this blog

How to mention the localhost in android -

php - Calling a template part from a post -

c# - String.format() DateTime With Arabic culture -