最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Node.js get pid of a spawned process - Stack Overflow

programmeradmin1浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 3

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;
}
发布评论

评论列表(0)

  1. 暂无评论