Getting the correct process id from child processes

So, I create several processes and try to calculate the PID of the process when it receives some data, here is 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 one 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.

+4
source share
2 answers

You are running a problem with the childProcess variable. JavaScript variables are a scope. Because of this, the variable is no exception to the loop.

A simplified example of code that acts as you have:

 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 closure so that the childProcess variable exists with this scope. The above code displays the expected 0, 1, 2

+5
source

Looks like a problem with closing. Pass the loop variable to the function so that the scope does not change.

 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('cmd.exe'); displayid(childProcess); } function displayid(childProcess){ childProcess.stdout.on('data', function(data) { console.log('stdout (' + childProcess.pid + '): ' + data); }); } 

Output

 stdout (368): Microsoft Windows [Version 6.2.9200] stdout (20268): Microsoft Windows [Version 6.2.9200] stdout (15728): Microsoft Windows [Version 6.2.9200] 

Without him

 stdout (10964): Microsoft Windows [Version 6.2.9200] stdout (10964): Microsoft Windows [Version 6.2.9200] stdout (10964): Microsoft Windows [Version 6.2.9200] 
+3
source

Source: https://habr.com/ru/post/1492110/


All Articles