如何在 10 秒后终止 node.js 中的子进程?

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

我正在制作一个在线代码运行器并且它运行良好但是当它 运行 进入无限循环然后它不会停止,所以如果它被执行得更多我想杀死这个子进程超过 10 秒如何在 10 秒后杀死 exec 进程?

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,
      });
    });
  });
};

我认为你可以将子进程保存在一个变量中,然后像那样杀死它

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);
  });
};

exec 有一个 timeout 选项可以用于此目的(参见 docs)。不需要特殊代码:

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