0

I'm testing with electron, it's the first time I've used it to package a desktop application. My application is composed of a frontend made in React and the backend in flask.

My flask application was packaged with pyinstaller, this app runs a local server on the PC where the electron application is opened

My problem is that when I run the application everything runs perfectly, but when I close it the local flask server remains running in the background, and I want the process to end when closing the app so as not to generate performance problems.

thread i'm talking about

I tried many things but I can't get the application to finish the process when closing the application. If anyone had a similar problem and can help me, I would be very grateful. Thanks.

This is the main.js electron config:

const { app, BrowserWindow } = require('electron');
const { execFile, exec } = require('child_process');
const path = require('path');
const kill = require('tree-kill');

let mainWindow;
let flaskProcess;

app.on('ready', () => {

    // Iniciar Flask

    flaskProcess = execFile(
      path.join(__dirname, 'back', 'dist', 'main.exe'),
      (error, stdout, stderr) => {
          if (error) {
              console.error(`Error al ejecutar el backend Flask: ${error.message}`);
          }
          if (stderr) {
              console.error(`Errores del backend Flask: ${stderr}`);
          }
      }
  );


    // Crear la ventana principal
    mainWindow = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
            preload: path.join(__dirname, 'preload.js'),
            nodeIntegration: true,
        },
    });

    // Cargar la aplicación React
    mainWindow.loadFile(path.join(__dirname, 'build', 'dist', 'index.html'));

    mainWindow.on('closed', () => {
        if (flaskProcess) {
            console.log('Cerrando el servidor Flask...');
            flaskProcess.kill('SIGKILL');
        }
        mainWindow = null;
    });
});

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
      app.quit();
    }
  });

// Detener Flask al salir
app.on('quit', () => {
    if (flaskProcess && !flaskProcess.killed) {
        console.log('Cerrando el servidor Flask...');
        kill(flaskProcess.pid, 'SIGKILL', (err) => {
            if (err) {
                console.error(`Error al cerrar el proceso: ${err.message}`);
            } else {
                console.log('Servidor Flask cerrado correctamente.');
            }
        }); // Fuerza la terminación del proceso
    }
});

As you can see I'm forcing the closure with SIGKILL, I also tried with SIGTERM, but neither of them works for me. I saw somewhere that you have to capture these signals from my flask backend in the following way

Flask code

import signal
import sys

def handle_exit(signal, frame):
    print('Cerrando Flask...')
    sys.exit(0)

signal.signal(signal.SIGINT, handle_exit)
signal.signal(signal.SIGTERM, handle_exit)

This is mi package.json electorn config

{
  "devDependencies": {
    "electron": "^34.0.0",
    "electron-builder": "^25.1.8"
  },
  "name": "appprueba",
  "version": "0.1.0",
  "description": "Aplicacion de prueba",
  "author": {
    "name": "Benja",
    "email": "[email protected]"
  },
  "main": "main.js",
  "scripts": {
    "build": "react-scripts build",
    "electron": "electron .",
    "dist": "electron-builder"
  },
  "build": {
    "appId": "com.appprueba.id",
    "productName": "Aplicacion Prueba",
    "directories": {
      "output": "dist"
    },
    "files": [
      "build/**/*",
      "back/**/*",
      "main.js",
      "preload.js"
    ],
    "extraFiles": [
      {
        "from": "back/dist/",
        "to": "back/dist/",
        "filter": [
          "**/*"
        ]
      }
    ],
    "mac": {
      "category": "public.app-category.utilities"
    },
    "win": {
      "target": "nsis",
      "requestedExecutionLevel": "requireAdministrator"
    },
    "linux": {
      "target": "AppImage"
    }
  },
  "asar": true,
  "dependencies": {
    "tree-kill": "^1.2.2"
  }
}

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.