Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the correct process id from child processes

Tags:

node.js

So, I'm spawning a few processes and trying to figure out the PID of the process when it gets some data, here's my code:

var mod_child_process = require('child_process');
var mod_events        = require('events');

for (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 always returns a 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.

like image 400
Anonymous Avatar asked Jul 18 '13 14:07

Anonymous


1 Answers

You're running into a scoping issue with the variable childProcess. Variables in JavaScript are function scoped. Because of this, the variable isn't exclusive to the loop.

Simplified example of code acting how you have it:

for (var i = 0; i < 3; ++i) {
    var someNumber = i;

    setTimeout(function() {
        console.log(someNumber);
    }, 100);
}

outputs: 2, 2, 2

And the fix:

for (var i = 0; i < 3; ++i) {
    (function() {
        var someNumber = i;

        setTimeout(function() {
            console.log(someNumber);
        }, 100);
    })();
}

You want to wrap your logic in a closure so that the variable childProcess exists with that scope. The above code outputs the expected 0, 1, 2

like image 138
Jay Avatar answered Nov 14 '22 22:11

Jay