电子杀死 child_process.exec [英] Electron kill child_process.exec

查看:43
本文介绍了电子杀死 child_process.exec的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an electron app that uses child_process.exec to run long running tasks. I am struggling to manage when the user exits the app during those tasks.

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

If they exit my app or hit close the child processes continue to run until they finish however the electron app window has already closed and exited.

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

Is there a way to notify the user that there are process still running and when they have finished then close the app window?

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

All I have in my main.js is the standard code:

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

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

Should I be adding a check somewhere?

感谢您的帮助

已编辑

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

I cannot seem to get the PID of the child_process until it has finished. This is my child_process code

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

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

Should I be trying to get it in a different way?

推荐答案

所以在大家的好评之后,我能够更新我的代码并添加一些附加功能以使其正常工作,所以我将我的更新发布给其他人.

So after everyones great comments I was able to update my code with a number of additions to get it to work, so am posting my updates for everyone else.

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

1) Change from child_process.exec to child_process.spawn

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

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

2) Use the Electron ipcRenderer to communicate from my module to the main.js script. This allows me to send the PIDs to main.js

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

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

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

3) Add those PIDs to array

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

4) In my main.js I added the following code to kill any PIDs that exist in the array before exiting the app.

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

感谢大家的帮助.

这篇关于电子杀死 child_process.exec的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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