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