Electron kill child_process.exec

后端 未结 3 963
旧巷少年郎
旧巷少年郎 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:39

    ChildProcess emits an exit event when the process has finished - if you keep track of the current processes in an array, and have them remove themselves after the exit event fires, you should be able to just foreach over the remaining ones running ChildProcess.kill() when you exit your app.

    This may not be 100% working code/not the best way of doing things, as I'm not in a position to test it right now, but it should be enough to set you down the right path.

    var processes = [];
    
    // Adding a process
    var newProcess = child_process.exec("mycommand");
    processes.push(newProcess);
    newProcess.on("exit", function () {
      processes.splice(processes.indexOf(newProcess), 1);
    });
    
    // App close handler
    app.on('window-all-closed', function() {
      if (process.platform != 'darwin') {
        processes.forEach(function(proc) {
          proc.kill();
        });
    
        app.quit();
      }
    });
    

    EDIT: As shreik mentioned in a comment, you could also just store the PIDs in the array instead of the ChildProcess objects, then use process.kill(pid) to kill them. Might be a little more efficient!

提交回复
热议问题