0

I'm building an online ide by running the command to execute the code by spawn... but what should I do if there is an infinite loop in the code...The process is not being stopped

const { childElements } = require("dom-helpers");
const path = require("path");

const executeCpp = (filepath) => {
  const file = path.basename(filepath[1].split(".")[0]);

  const execute = new Promise((resolve, reject) => {
    const run = spawn(
      `cd ${filepath[0]} && g++ ${file}.cpp -o ${file}.out && ./${file}.out < ${file}.txt`,
      {
        shell: true,
      }
      // (error, stdout, stderr) => {
      //   error && reject({ error, stderr });
      //   stderr && reject(stderr);
      //   resolve(stdout);
      // }
    );
    setTimeout(() => {
      run.kill();
    }, 2000);

    run.on("exit", (code) => {
      // clearTimeout(to);
      resolve(`Process Exited with code ${code}`);
    });
    run.stderr.on("data", (data) => {
      resolve(String(data));
      console.log(data)
    });
    run.stdout.on("data", (data) => {
      resolve(data);
      console.log(data)
    });

  });

  return execute;
};
module.exports = {
  executeCpp,
};

This is my workaround, but it is not working. Also, when I use exec, I can reject the promise if there is an error, but it's not working; instead, I need to resolve the promise even if there is an error.

Aditya Harsh
  • 21
  • 1
  • 4
  • 1
    If you know it's stuck forever, and you need it to stop, [kill the process](https://nodejs.org/dist/latest-v16.x/docs/api/child_process.html#child_process_subprocess_kill_signal). – Mike 'Pomax' Kamermans Sep 12 '21 at 04:31
  • Ya, but how to kill the process... I tried to kill the process with setTimeout but it's not working..have a look in code above – Aditya Harsh Sep 12 '21 at 04:39
  • 1
    "it's not working" is not a problem description: describe what you see happening to make you conclude that `.kill()` isn't doing what it's supposed to do. – Mike 'Pomax' Kamermans Sep 12 '21 at 14:49

0 Answers0