windows上的电子和节点,杀死一个产生的进程 [英] electron and node on windows, kill a spawned process
问题描述
我正在从电子主程序启动一个后台进程(在 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 没有结果:只有第一个进程(来自例如)被杀死,第二个(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
不会杀死它.
also exec taskkill /F /T /PID
doesn't kill it.
杀死的唯一方法是执行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 上的进程管理中遗漏了一些明显的东西?
i'm missing something obvious on process management on windows?
推荐答案
我在 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.
这篇关于windows上的电子和节点,杀死一个产生的进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!