2

我想使用 bash 并行运行多个进程。我做了以下事情:

./proc sth1 & ./proc sth2 & ./proc sth3 & ... & ./proc sthN &

上面的问题是它立即结束。所以如果我这样做: time (./proc sth1 & ... & ./proc sthN &)我回来了0

我想运行上面的命令,但我希望它在最后一个进程完成后停止。所以 if./proc sthX需要 10 秒,而所有其他进程需要 1 秒。我想等待 10 秒,直到上面的命令返回。有没有办法做到这一点?

4

4 回答 4

6

最后打电话wait就行了。引用 bash manual Job control builtins

wait [jobspec or pid ...]

等待每个进程 ID pid 或作业规范 jobspec 指定的子进程退出,并返回最后等待的命令的退出状态。如果给出了作业规范,则等待作业中的所有进程。如果没有给出参数,则等待所有当前活动的子进程,并且返回状态为零。如果 jobspec 和 pid 都没有指定 shell 的活动子进程,则返回状态为 127。

一个例子:

#!/bin/bash
function test {
    time=$(( RANDOM % 10 ))
    echo "Sleeping for $time"
    sleep "$time"
    echo "Slept for $time"
}

time (
    test & test & test & test & test & test &
    wait
    echo "Finished all."
)
于 2013-11-03T17:42:55.910 回答
1

wait专为此设计:

./proc sth1 & ./proc sth2 & ./proc sth3 & ... & ./proc sthN &
 wait

一些文档:

$ LANG=C help wait
wait: wait [id]
    Wait for job completion and return exit status.

    Waits for the process identified by ID, which may be a process ID or a
    job specification, and reports its termination status.  If ID is not
    given, waits for all currently active child processes, and the return
    status is zero.  If ID is a a job specification, waits for all processes
    in the job's pipeline.

    Exit Status:
    Returns the

身份证状态;如果 ID 无效或给出的选项无效,则失败。

另一种解决方案是获取所有 pid 并wait为所有这些 pid 放置一个。

于 2013-11-03T17:25:40.933 回答
0

wait与作业列表一起使用的另一个示例:

nbf=0
jobs -p|while read -r; do
    wait $REPLY || (( nbf++ ))
done
echo "$nbf jobs ended with failure" >&2
于 2013-11-03T18:07:34.207 回答
0

虽然“等待和组合”可能就足够了,但我发现大多数时候这不是我想要的。我想要的是返回代码将指示失败,以防任何命令默认失败。所以我创建了一个名为的小实用程序par

https://github.com/k-bx/par

于 2015-04-08T14:30:42.420 回答