0

I am creating a child_process which will just open a command prompt whenever user click on a Button. If user clicks on the button 3 times. then 3 times a command prompt is created. Instead of creating 3 command prompt, I want to show the already created process(command prompt), means I want only one instance of command prompt.

const { exec } = require('child_process');

export async function executeCommand(commandLine, execOptions) {
  return await new Promise((resolve, reject) => {
    if (execOptions.env) {
      for (var prop in execOptions.env) {
        if (execOptions.env.hasOwnProperty(prop)) {
          process.env[prop] = execOptions.env[prop];
        }
      }
      delete execOptions.env;
    }
    exec(commandLine, execOptions, (error, stdout, stderr) => {
      console.debug(stdout);
      if (error) {
        console.debug(stderr);
        console.debug(error);
        reject(error);
      }
      else if (stderr) {
        console.debug(stderr);
        reject(stderr);
      }
      else {
        resolve(stdout);
      }
    });
  });
}

Please help me in solving this issue.

Ranjan V
  • 21
  • 4

1 Answers1

0

When you start a process you can set a boolean to keep track. On close, you can set the boolean to false. This will prevent any new processes from being created while one is running. However, I don't know of a way to bring a process' window to the front if the user has put it elsewhere. You could simply notify the user that a process is already running.

let running = false;

export async function executeCommand(commandLine, execOptions) {
  return await new Promise((resolve, reject) => {
    ...
    if (!running) {
      exec(commandLine, execOptions, (error, stdout, stderr) => {
        ...
      }).addListener("close", () => (running = false));
      running = true;
    }
  });
}

Alternatively you can save the process itself so you can log information about it

let proc;

export async function executeCommand(commandLine, execOptions) {
  return await new Promise((resolve, reject) => {
    ...
    if (!proc) {
      proc = exec(commandLine, execOptions, (error, stdout, stderr) => {
        ...
      }).addListener("close", () => (proc = null));
    } else {
      console.log("Process already running: ", proc.spawnfile, proc.spawnargs);
    }
  });
}

Depending on your use, it may be more fitting to use the exit event instead of close.

Chris Hamilton
  • 9,252
  • 1
  • 9
  • 26
  • Thank you, now only one instance of command prompt is popping up, but after closing the command prompt , if we had clicked on install button 2 times earlier, then again 2 command prompts are popping up once we close the initial created command prompt. – Ranjan V Mar 15 '22 at 09:47