Electron kill child_process.exec

后端 未结 3 1008
旧巷少年郎
旧巷少年郎 2021-02-04 05:15

I have an electron app that uses child_process.exec to run long running tasks. I am struggling to manage when the user exits the app during those tasks.

I

3条回答
  •  甜味超标
    2021-02-04 05:28

    Another solution. If you want to keep using exec()

    In order to kill the child process running by exec() take a look to the module ps-tree. They exaplain what is happening.

    in UNIX, a process may terminate by using the exit call, and it's parent process may wait for that event by using the wait system call. the wait system call returns the process identifier of a terminated child, so that the parent tell which of the possibly many children has terminated. If the parent terminates, however, all it's children have assigned as their new parent the init process. Thus, the children still have a parent to collect their status and execution statistics. (from "operating system concepts")

    SOLUTION: use ps-tree to get all processes that a child_process may have started, so that they

    exec() actually works like this:

    function exec (cmd, cb) {
      spawn('sh', ['-c', cmd]);
      ...
    }
    

    So check the example and adapt it to your needs

    var cp = require('child_process'),
    psTree = require('ps-tree');
    
    var child = cp.exec("node -e 'while (true);'", function () { /*...*/ });
    
    psTree(child.pid, function (err, children) {
        cp.spawn('kill', ['-9'].concat(children.map(function (p) { return p.PID })));
    });
    

提交回复
热议问题