【问题标题】:Await NodeJS exec and then kill all child processes等待 NodeJS exec 然后杀死所有子进程
【发布时间】:2018-07-20 16:12:01
【问题描述】:

Aim - 使用 NodeJS exec 执行 shell 命令。等待它的回应有两个原因:-

  1. 我想用exec一一执行多个命令。
  2. 我想测量每个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


    【解决方案1】:

    node-exec-promise 无法做到这一点:

    1. promiseexec 返回 stdoutstderr,而不是 ChildProcess 对象。
    2. promise 只会在它解析或拒绝时返回某些内容,因此即使 promiseexec 会返回 ChildProcess 对象,您也只能在命令完成/失败后获得它。
    3. promiseexec 只接受一个参数,因此您的超时选项将被忽略。

    您要么必须使用将返回正确子进程对象(包括.pid)的普通回调样式,要么将其包装到具有取消功能的bluebird 中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-13
      • 2014-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多