简体   繁体   中英

Await NodeJS exec and then kill all child processes

Aim - Execute a shell command using NodeJS exec . Await it's response because of 2 reasons:-

  1. I want to execute multiple commands one by one using exec .
  2. I want to measure the time of execution by each exec .

Now since exec does not returns a promise I am using the library node-exec-promise

Problem - There is a chance that my exec command goes into an infinite loop. I would like to kill the process if it does so.

The NodeJS exec allows us to pass a timeout parameter. However it is not killing all the child processes. So in order to do that I am using tree-kill library. In order to use tree-kill I have to get the pid of the process which the node-exec-library does not returns. How do I get the pid from the library node-exec-promise

Relevant code -

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
}

Also this maybe a completely wrong way of doing things. If so, please suggest an alternative.

This won't be possible with node-exec-promise :

  1. promiseexec returns stdout and stderr , not the ChildProcess object.
  2. A promise only ever returns something when it resolves or rejects, so even if promiseexec would return the ChildProcess object, you would only get it after the command completed/failed.
  3. promiseexec only accepts a single parameter, so your timeout option is ignored.

You will either have to use the vanilla callback style which will return a proper subprocess object (including .pid ) or wrap it into bluebird which has a cancellation feature.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM