如何并行生成五个子进程

How to spawn five child processes in parallel

我想运行 并行执行五个生成命令。我将五个 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();
}