如何解决如何并行生成五个子进程
我想并行运行五个 spawn 命令。我将五个 hls 流 url 传递给循环,这些流链接命令应该将视频录制 5 秒钟,然后终止这些进程。
我尝试以多种方式异步执行...但我不知道如何为每个流独立等待 5 秒。
我在 Windows 10 上运行这个。
这是我尝试的最后一件事:
import { spawn } from "child_process";
import crypto from "crypto"
const hls_streams = [
'https://stream1.url','https://stream2.url','https://stream3.url','https://stream4.url','https://stream5.url',]
for (let i = 0; i < hls_streams.length; i++) {
const filename = crypto.randomBytes(16).toString("hex");
const child = spawn('streamlink',[`${urls[i]}`,"best","-f","-o",`/temp/${filename}.mp4`]);
await new Promise(r => setTimeout(r,5000));
child.kill()
}
对于五个 url 的正确执行应该只持续 5 秒...
解决方法
你可以使用一个循环来创建一个子数组,然后等待,然后另一个循环来结束它们。对于基于现有数组创建数组,map()
可能更方便:
import { spawn } from "child_process";
import crypto from "crypto";
const hls_streams = [
'https://stream1.url','https://stream2.url','https://stream3.url','https://stream4.url','https://stream5.url',];
let children = hls_streams.map(url => {
const filename = crypto.randomBytes(16).toString("hex");
const child = spawn('streamlink',[`${url}`,"best","-f","-o",`/temp/${filename}.mp4`]);
return child;
});
await new Promise(r => setTimeout(r,5000));
for(let child of children) {
child.kill();
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。