admin管理员组文章数量:1122846
I’m developing an Electron app that uses a Python executable as a backend server. The Python backend is spawned using child_process.spawn. While the app works fine most of the time, I’ve noticed that when the user quits the app, the Python backend process doesn’t always terminate. This leads to zombie processes running in the background, which is problematic.
This spawns the python exe:
const { spawn } = require("child_process");
const kill = require("tree-kill");
let pythonBackend;
function startBackend() {
pythonBackend = spawn("path/to/python_backend.exe");
pythonBackend.stdout.on("data", (data) => {
console.log(`stdout: ${data}`);
});
pythonBackend.stderr.on("data", (data) => {
console.error(`stderr: ${data}`);
});
pythonBackend.on("close", (code) => {
console.log(`child process exited with code ${code}`);
});
}
And this attempts to stop it
async function stopBackend() {
if (pythonBackend) {
if (process.platform === "win32") {
exec(`taskkill /PID ${pythonBackend.pid} /T /F`, (err) => {
if (err) {
console.error("Failed to kill process:", err);
} else {
console.log("Process killed");
}
});
} else {
kill(pythonBackend.pid, "SIGTERM", (err) => {
if (err) {
console.error("Failed to kill process:", err);
} else {
console.log("Python process and its children killed");
}
});
}
pythonBackend = null;
}
}
app.on("before-quit", stopBackend);
app.on("quit", stopBackend);
app.on("window-all-closed", () => {
if (process.platform !== "darwin") {
app.quit();
}
});
process.on("exit", stopBackend);
process.on("SIGINT", () => {
stopBackend();
process.exit(0);
});
Neither on mac or on windows it kills the python process consequently. Sometimes it just doesnt do anything without any feedback. My question: Is there a foolproof way to ensure the python exe is always killed when quitting the electron app?
本文标签: javascriptHow to properly kill python process spawned by electron appStack Overflow
版权声明:本文标题:javascript - How to properly kill python process spawned by electron app? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736304599a1932291.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论