因此,我正在开发一个 Electron 应用程序,该应用程序应在按下按钮时启动外部应用程序。它可以工作,但是如果我关闭该应用程序并再次按下按钮,它将启动该过程的多个实例。这是代码:

ipcMain.on("run_crystal", () => {
  var cp = require("child_process");
  executablePath = crystal + "\\CrystalDM\\Server\\CrystalDMServer.exe";
  var Server_child = cp.spawn(executablePath);
  executablePath = crystal + "\\CrystalDM\\Game\\CrystalDM.exe";
  var parameters = ["test"];
  var options = {cwd:crystal+"\\CrystalDM\\Game"};
  console.log("a intrat in start game si urmeaza sa ruleze " + executablePath)
  var Game_child = cp.execFile(executablePath, parameters, options, (error, stdout, stderr) =>{
    console.log(stdout)
    Game_child.kill("SIGINT");
    Server_child.kill("SIGINT");
    delete Game_child;
    delete Server_child;
    delete cp;
  });
});

最佳答案

这段代码可能被多次调用,您忘了在完成操作后删除事件监听器。我不知道如何解决它,但是请尝试以下操作:

ipcMain.once("run_crystal", () => {
   [your code here]
});

或者:
ipcMain.on("run_crystal", () => {
   [your code here]
   ipcMain.removeAllListeners("run_crystal");
});

10-06 15:06