Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

electron and node on windows, kill a spawned process

i'm starting a background process (on windows) from electron main, something like this:

app_exe = require("child_process").spawn(
  "app.exe" ,
  [ "--params", ... ],
  { stdio: "ignore" }
);

this works fine, i can see this from process explorer: enter image description here

but i cannot kill the process when the electron is closed ( .on("closed") or on("window-all-closed") )

i tried child.kill([signal]), but also tree-kill or taskkill with no results: only the first process (6036 from the example) is killed, the second (5760) remains stale.

also exec taskkill /F /T /PID doesn't kill it.

the only way to kill is exec taskkill /F /IM app.exe /T, but in this way i cannot run two instances of the electron app.

i'm missing something obvious on process management on windows?

like image 493
robert laing Avatar asked Feb 09 '17 15:02

robert laing


People also ask

How do you kill a process in a Nodejs process?

exit(1); //process exited with code 1 nodejs }), 5000); You can also use the process. exitCode for terminating the Node.

Which key is used to kill a process in node JS?

kill() Method. The process. kill( pid[,signal] ) is an inbuilt method of node. js which sends a signal to the process, pid (which is the process id) and signal is in the string format that is the signal to send.

Does electron run on Windows?

Compatible with Mac, Windows, and Linux, Electron apps build and run on three platforms.


1 Answers

I was seeing a similar issue on Windows 7 machines. I believe newer OS' will automatically kill the child processes.

What I had to do was to just save off the PID of the spawned-process and send it a SIGTERM message to kill it when all the windows closed. Now, if there's a chance that the process died by other means before the Electron app shut down, the OS may have recycled the child process' PID, so for extra robustness, I used the find-process npm module to make sure that the PID that I held on to is associated with the correct process.

const proc = cp.spawn("app.exe");

app.on("window-all-closed", async () => {
    const list = await require("find-process")("pid", proc.pid);
    app.quit();
    if (list[0] && list[0].name.toLowerCase() === "app.exe")
        process.kill(proc.pid);
});

Now if your Electron app does not exit gracefully (and the above code isn't run), you'd have to rely on another technique.

If you control the child process that you're spawning, you can try to kick off a thread that listens to or pings the main process. If it doesn't see the main process, it can kill itself.

If you don't control the spawned-app, then I'm out of ideas, but the above code will handle most cases.

like image 176
pushkin Avatar answered Sep 17 '22 09:09

pushkin