首页 > 解决方案 > 如何在超时后杀死 spawnSync

问题描述

我想杀死 ES6 async / await 中的 spawnSync 进程。

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

如果第二个 spawnSync exeRst 需要很长时间,它将在 2 秒内停止执行。

test.py 需要 10 秒或更长时间才能运行。

但是,由于等待,setTimeout 将在 test.py 的所有执行结束后的 10 秒后执行。

如何让跑步不能超过 2 秒?

标签: javascriptnode.jschild-processspawn

解决方案


spawnSync支持一个名为timeout. 这以毫秒为单位指定允许进程运行多长时间:

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

推荐阅读