Search code examples
javascriptnode.jschild-processspawn

How to kill spawnSync after a timeout


I want to kill the spawnSync process in ES6 async / await.

  (async () => {
    const type = 'python';
    const exefile = './test.py';
    let opt = [file];

    let result = await spawnSync(type, opt, {
      encoding: 'utf-8'
    });

    if (exefile !== '') {

      const exeRst = await spawnSync(exefile, {
        encoding: 'utf-8'
      });

      setTimeout(() => {
        console.log('⏰ Timeout!!');
        console.log('exeResult.pid : ', exeResult.pid);
        exeResult.kill();
      }, 2000);

      if (
        result.output['1'] === '' &&
        result.output['2'] === '' &&
        exeRst.output['1'] !== ''
      ) {
        console.log('💦exeResult:', exeRst);
        console.log('💦result:', result.output);
      }
    }
  })();

If the second spawnSync exeRst takes a long time, it will stop executing within 2 seconds.

test.py takes 10 seconds or more to run.

However, due to await, setTimeout will be executed after 10 seconds after all the execution of test.py has ended.

How do I make it impossible to run for more than 2 seconds?


Solution

  • spawnSync supports an option field called timeout. This specifies in milliseconds how long the process is allowed to run:

    await spawnSync(exefile, {
            encoding: 'utf-8',
            timeout: 2000
          });