电子和窗户上的节点,杀死产生的过程 [英] electron and node on windows, kill a spawned process

查看:85
本文介绍了电子和窗户上的节点,杀死产生的过程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从电子主电源启动Windows上的后台进程,如下所示:

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:

,但是当电子关闭时,我无法终止该过程( .on( closed) on( window-all-closed)

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

我尝试了 child.kill([signal]),也 tree-kill taskkill 无结果:仅第一个进程(示例中为6036)被杀死,第二个(5760)仍然过时。

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.

exec taskkill / F / T / PID 也不杀死

唯一杀死的方法是exec taskkill / F / IM app.exe / T ,但是这样我就不能运行两个电子应用程序实例。

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.

我缺少了一些东西

推荐答案

我在Windows 7计算机上看到了类似的问题。我相信较新的操作系统会自动终止子进程。

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

我要做的就是保存生成的进程的PID,并向其发送 SIGTERM 消息可在所有窗口关闭时将其杀死。现在,如果在Electron应用程序关闭之前,该进程有可能因其他方式终止运行,则操作系统可能已回收了子进程的PID,因此,为了增强鲁棒性,我使用了 find-process npm模块以确保我持有的PID

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);
});

现在,如果您的Electron应用无法正常退出(并且上述代码未运行),您

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

如果您控制要生成的子进程,则可以尝试启动一个监听或ping该进程的线程。主要过程。如果没有看到主要过程,它会杀死自己。

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.

这篇关于电子和窗户上的节点,杀死产生的过程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆