首页 > 解决方案 > Electron exec 启动多个进程

问题描述

我正在创建一个启动 .exe 文件的电子应用程序。我使用 exec 这样做,因为它需要特殊的参数。在渲染器中,我有一个启动它的按钮,如果我多次单击该按钮,它将多次执行 .exe 文件,因此如果我第二次单击它,它将启动 2 个 .exe 文件。这是我在渲染器中的代码:

$(".buttonJSMain").click(function() {
    ipcRenderer.send("download-lc");

    ipcRenderer.on("downloaded-lc", (event) => {
        var authType = 'authType';
        var username = 'username';
        var password = 'password';
        var memory = 'memory';

        var arguments = authType + " " + username + " " + password + " " + memory;
        ipcRenderer.send('run', arguments);
    });
})

这是我在主线程中的代码:

ipcMain.on('run', (event, arguments) => {
  var child = require('child_process').execFile;
  var args = arguments;

  try {
    exec("file.exe " + arguments, (error, stdout, stderr);
  } catch {
    console.log('Couldn\'t start')
  }
})

我怎样才能使它只启动一次文件?

标签: javascriptelectron

解决方案


使用注释中所述的全局布尔标志。

let running = false // global flag

ipcMain.on('run', (event, arguments) => {
  var child = require('child_process').execFile;
  var args = arguments;

  try {
    if ( running === false ) { // no instance is running
      running = true; // state you are about to run
      exec("file.exe " + arguments, (error, stdout, stderr);
      running = false; // let others to run
    }
    else {
      console.log("Another instance is running");
    }
  } catch {
    running = false
    console.log('Couldn\'t start')
  }
})

推荐阅读