I am experimenting with node.js. Trying to spawn processes but cannot seem to get the right PID back on close. If i run the function below it will spawn a process but the returning ls.pid in the on close function will always be the pid from the last process.
function app_cmd(cmd, args,path) {
ls = spawn ( cmd , args , { cwd : path } );
console.log ( cmd +' ' + ls.pid );
ls.on ( 'close' , function(code) {
console.log ( 'returning: ' + code + ' on ' + ls.pid );
} );
return ls.pid;
}
So if i call the function twice i get the following output (note the two times 6940 in the return):
php.exe 6076
php.exe 6940
returning: 0 on 6940
returning: 0 on 6940
Anyone has a pointer for me on how to get the proper PID back in the onClose?
Much appreciated,
Ties
I am experimenting with node.js. Trying to spawn processes but cannot seem to get the right PID back on close. If i run the function below it will spawn a process but the returning ls.pid in the on close function will always be the pid from the last process.
function app_cmd(cmd, args,path) {
ls = spawn ( cmd , args , { cwd : path } );
console.log ( cmd +' ' + ls.pid );
ls.on ( 'close' , function(code) {
console.log ( 'returning: ' + code + ' on ' + ls.pid );
} );
return ls.pid;
}
So if i call the function twice i get the following output (note the two times 6940 in the return):
php.exe 6076
php.exe 6940
returning: 0 on 6940
returning: 0 on 6940
Anyone has a pointer for me on how to get the proper PID back in the onClose?
Much appreciated,
Ties
Share asked Apr 3, 2018 at 18:50 Ties VandykeTies Vandyke 1541 silver badge8 bronze badges 2- 1 Well written question with a rep of 1. Thanks! – Randy Casburn Commented Apr 3, 2018 at 18:55
- 1 this is just another flavor of stackoverflow./questions/750486/… where instead of a loop doing the work, you're calling the function twice. Ensuring that the variable being used isn't shared between calls resolves the issue. – Kevin B Commented Apr 3, 2018 at 19:04
1 Answer
Reset to default 3It looks like you're declarling ls
as a global by mistake causing it to be overwritten the second time, adding a var|let|const
should fix it.
function app_cmd(cmd, args,path) {
const ls = spawn ( cmd , args , { cwd : path } );
console.log ( cmd +' ' + ls.pid );
ls.on ( 'close' , function(code) {
console.log ( 'returning: ' + code + ' on ' + ls.pid );
} );
return ls.pid;
}