一位技术博客作者发布了一种在 Bash 中实现并发命令队列的方法,该方案利用 mkfifo、文件描述符和 xargs -P 来限制并行执行的任务数量 1。其核心机制是通过 mkfifo 创建命名管道作为队列,并使用 xargs -P 管理最大并发数 1。
作者提供了包含 queue_start(初始化队列)、queue_submit(提交命令)和 queue_wait(等待队列排空)三个主要函数的完整代码实现及使用示例 1。该代码适用于 Bash 和 Zsh 1。
作者讨论了该方案的已知局限性:一个 Shell 只能有一个活动队列;为避免输出交错,命令输出不采用流式传输方式;且 queue_wait 不返回具体的作业失败状态码 1。针对命令预先已知的场景,作者指出直接使用 xargs -0 -n 1 -P N 或 GNU parallel 是更优的替代方案 1。
A technical tutorial has been published demonstrating how to implement concurrent command queues within Bash, utilizing named pipes created by mkfifo and file descriptors to manage task execution. 1 The core mechanism relies on xargs -P to limit the number of tasks running in parallel. 1
The implementation provides three primary functions: queue_start for initializing the queue, queue_submit for adding commands, and queue_wait to pause execution until all queued tasks have finished. 1 While the code is designed to be compatible with both Bash and Zsh environments, the author notes specific limitations, such as the constraint that only one active queue can exist per shell instance. 1 Additionally, command output is not streamed to prevent interleaving issues, and the queue_wait function does not return specific failure status codes for individual jobs. 1 For scenarios where the list of commands is known beforehand, the article suggests that using xargs -0 -n 1 -P N or GNU Parallel may offer a simpler alternative without the need for custom queue logic. 1
评论
还没有评论,欢迎留下第一条。