Arnav
Arnav

Reputation: 117

How to kill a child process in node.js after 10 sec?

I am making an online code runner and it is working well but when it is running into an infinite loop then it is not stopping, so I want to kill this child process if it is being executed more than 10 sec. How can kill the exec process after 10s?

export const javascriptExecuter = (data, input) => {
  return new Promise((resolve, reject) => {
    const fileName = "code.js";

    saveFile(fileName, data).then(() => {
      fs.writeFile("jsinput.txt", input, (err) => {
        if (err) {
          reject("internal server error ...");
        }
      });
    });

    setTimeout(() => {
       // I WANT TO KILL THE PROCESS AFTER 10 SEC IF IT IS RUNNING **********
    }, 10000);

    exec("node " + fileName + " < " + "jsinput.txt", (err, stdout, stderr) => {
      if (err) {
        resolve({
          err: true,
          output: err,
          error: stderr,
        });
      }
      resolve({
        err: false,
        output: stdout,
      });
    });
  });
};

Upvotes: 0

Views: 1018

Answers (2)

Christian Fritz
Christian Fritz

Reputation: 21364

exec has a timeout option you can use for this (see docs). No need for special code:

exec("node " + fileName + " < " + "jsinput.txt", {timeout: 10000},
  (err, stdout, stderr) => { ... });

Upvotes: 3

Liad
Liad

Reputation: 844

i think you can save the child process in a variable and then kill it like that

export const javascriptExecuter = (data, input) => {
  return new Promise((resolve, reject) => {
    const fileName = "code.js";

    saveFile(fileName, data).then(() => {
      fs.writeFile("jsinput.txt", input, (err) => {
        if (err) {
          reject("internal server error ...");
        }
      });
    });

    // save the process in a const
    const childProcess = exec("node " + fileName + " < " + "jsinput.txt", (err, stdout, stderr) => {
      if (err) {
        resolve({
          err: true,
          output: err,
          error: stderr,
        });
      }
      resolve({
        err: false,
        output: stdout,
      });
    });

    setTimeout(() => {
       // kill it
       childProcess.kill()
    }, 10000);
  });
};

Upvotes: 0

Related Questions