gpt4 book ai didi

javascript - 如何在超时后杀死 spawnSync

转载 作者:行者123 更新时间:2023-11-30 19:29:01 25 4
gpt4 key购买 nike

我想在 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 秒或更长时间才能运行。

但是由于await,setTimeout会在test.py全部执行结束后10秒后执行。

如何使运行时间不能超过 2 秒?

最佳答案

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

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

关于javascript - 如何在超时后杀死 spawnSync,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56627983/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com