gpt4 book ai didi

node.js - Electron 杀死 child_process.exec

转载 作者:IT老高 更新时间:2023-10-28 23:15:02 26 4
gpt4 key购买 nike

我有一个 Electron 应用程序,它使用 child_process.exec 来运行长时间运行的任务。 当用户在这些任务期间退出应用程序时,我正在努力管理。

如果他们退出我的应用程序或点击关闭,子进程将继续运行直到它们完成,但是 Electron 应用程序窗口已经关闭并退出。

有没有办法通知用户有进程仍在运行,当他们完成后关闭应用程序窗口?

我的 main.js 中只有标准代码:

// Quit when all windows are closed.
app.on('window-all-closed', function() {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform != 'darwin') {
app.quit();
}
});

我应该在某处添加支票吗?

感谢您的帮助

已编辑

child_process 完成之前,我似乎无法获得它的 PID。这是我的 child_process 代码

var loader = child_process.exec(cmd, function(error, stdout, stderr) {
console.log(loader.pid)
if (error) {
console.log(error.message);
}
console.log('Loaded: ', value);
});

我应该尝试以不同的方式获得它吗?

最佳答案

因此,在大家的好评之后,我能够通过一些添加来更新我的代码以使其正常工作,所以我将我的更新发布给其他人。

1) 从 child_process.exec 更改为 child_process.spawn

var loader = child_process.spawn('program', options, { detached: true })

2) 使用 Electron ipcRenderer 从我的模块与 main.js 脚本进行通信。这允许我将 PID 发送到 main.js

ipcRenderer.send('pid-message', loader.pid);

ipcMain.on('pid-message', function(event, arg) {
console.log('Main:', arg);
pids.push(arg);
});

3) 将这些 PID 添加到数组中

4) 在我的 main.js 中,我添加了以下代码以在退出应用程序之前终止数组中存在的任何 PID。

// App close handler
app.on('before-quit', function() {
pids.forEach(function(pid) {
// A simple pid lookup
ps.kill( pid, function( err ) {
if (err) {
throw new Error( err );
}
else {
console.log( 'Process %s has been killed!', pid );
}
});
});
});

感谢大家的帮助。

关于node.js - Electron 杀死 child_process.exec,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36031465/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com