【问题标题】:How to kill spawnSync after a timeout如何在超时后杀死 spawnSync
【发布时间】:2019-06-17 08:59:00
【问题描述】:

我想杀死 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 秒?

【问题讨论】:

    标签: javascript node.js child-process spawn


    【解决方案1】:

    spawnSync 支持名为timeout 的选项字段。这以毫秒为单位指定进程允许运行多长时间:

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

    【讨论】:

    • 哇!!它在 node.js 文档中。感谢您的明确答复。
    猜你喜欢
    • 2016-04-22
    • 2012-05-30
    • 2011-07-06
    • 1970-01-01
    • 2012-11-18
    • 2021-07-30
    • 1970-01-01
    • 2013-07-24
    • 2022-10-16
    相关资源
    最近更新 更多