Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js get pid of a spawned process

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

like image 923
Ties Vandyke Avatar asked Oct 16 '22 20:10

Ties Vandyke


1 Answers

It 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;
}
like image 177
generalhenry Avatar answered Oct 20 '22 01:10

generalhenry