[英]How to spawn five child processes in parallel
I want to run five spawn commands in parallel.我想并行运行五个 spawn 命令。 I pass five hls stream urls to the loop, and these streamlink commands should record the video for 5 seconds and then kill those processes.
我将五个 hls stream url 传递给循环,这些流链接命令应该将视频录制 5 秒钟,然后终止这些进程。
I tried to do it async in several ways... but I don't know how to wait those 5 seconds independently for each stream.我尝试以多种方式异步执行...但我不知道如何为每个 stream 独立等待这 5 秒。
I'm running this on windows 10.我在 windows 10 上运行它。
Here's the last thing I tried:这是我尝试的最后一件事:
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()
}
A correct execution should last only 5 seconds for the five urls...五个 url 的正确执行应该只持续 5 秒......
You could use a loop for creating an array of children, then wait, then another loop for ending them.您可以使用一个循环来创建一个子数组,然后等待,然后另一个循环来结束它们。 For creating an array based on an already existing one,
map()
may be more convenient:对于基于已经存在的数组创建数组,
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.