[英]Node.js get pid of a spawned process
I am experimenting with node.js. 我正在尝试node.js. Trying to spawn processes but cannot seem to get the right PID back on close.
试图产生进程,但似乎无法在关闭时获得正确的PID。 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.
如果我运行下面的函数,它将生成一个进程,但on close函数中返回的ls.pid将始终是最后一个进程的pid。
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): 因此,如果我调用该函数两次,我会得到以下输出(请注意返回中的两次6940):
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? 任何人都有一个指针,告诉我如何在onClose中获得正确的PID?
Much appreciated, 非常感激,
Ties 领带
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. 看起来你错误地将
ls
声称为全局,导致它被第二次覆盖,添加var|let|const
应该修复它。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.