Reputation: 1401
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:
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?
Upvotes: 14
Views: 10694
Reputation: 1
You can try it with this code:
ipcMain.on('exampletab:close', () => {
ipcMain.removeAllListeners();
exampleWindow.close();
});
This code save my lot of time. When you close your child window, then use removeAllListeners()
to remove Previous closed Windows.
Upvotes: 0
Reputation: 10209
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.
Upvotes: 3
Reputation: 421
I had exactly the same issue, and no question / answer on the forums could resolve that problem. So after some research i've found a simple workaround and im sharing it :
// Workaround to close all processes / sub-processes after closing the app
electron.app.once('window-all-closed', electron.app.quit);
electron.app.once('before-quit', () => {
window.removeAllListeners('close');
});
And its working perfectly for me, hope it does for you.
Upvotes: 1