【发布时间】:2018-07-20 16:12:01
【问题描述】:
Aim - 使用 NodeJS exec 执行 shell 命令。等待它的回应有两个原因:-
- 我想用
exec一一执行多个命令。 - 我想测量每个
exec的执行时间。
现在由于 exec 没有返回承诺,我正在使用库 node-exec-promise
问题 - 我的exec 命令有可能进入无限循环。
如果它这样做,我想终止该进程。
NodeJS exec 允许我们传递 timeout 参数。然而,它并没有杀死所有的子进程。所以为了做到这一点,我正在使用tree-kill 库。为了使用 tree-kill 我必须获得 node-exec-library 不返回的进程的pid。如何从库node-exec-promise 中获取pid
相关代码 -
var promiseexec = require('node-exec-promise').exec;
var kill = require('tree-kill');
async functionOne(params){
for (let i = 0; i < arr.length; i++) {
let item = arr[i];
let start = now();
const p = await this.functionTwo(params);
let end = now();
console.log(p.pid); // undefined logs here
kill(p.pid, 'SIGKILL', function(err) {
console.log(err);
});
let time = ((end-start)/1000).toFixed(3)
console.log(time);
}
}
async functionTwo(params){
const p = await promiseexec(command, {timeout: 10000}, (error,stdout,stderr) => {
if(error!=null){
console.log(error);
}
});
return p; //this p is not the one that NodeJs exec returns
}
这也可能是一种完全错误的做事方式。如果是这样,请提出替代方案。
【问题讨论】:
标签: javascript node.js async-await