2

bash を使用して複数のプロセスを並行して実行したい。私は次のことをしました:

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

上記の問題は、すぐに終了することです。もしそうなら: time (./proc sth1 & ... & ./proc sthN &)私は戻ってき0ます。

上記のコマンドを実行したいのですが、最後のプロセスが終了したら停止したいです。そのため、他のすべてのプロセスが 1 秒かかるのに対し、if./proc sthXは 10 秒かかります。上記のコマンドが戻るまで 10 秒待ちたいと思います。これを行う方法はありますか?

4

4 に答える 4

6

wait最後に電話するだけです。bashマニュアルのジョブ制御ビルトインを引用:

wait [jobspec or pid ...]

各プロセス ID pid またはジョブ指定 jobspec で指定された子プロセスが終了するまで待機し、最後に待機したコマンドの終了ステータスを返します。ジョブ仕様が指定されている場合、ジョブ内のすべてのプロセスが待機されます。引数が指定されていない場合、現在アクティブなすべての子プロセスが待機され、戻りステータスはゼロになります。jobspec も pid もシェルのアクティブな子プロセスを指定しない場合、返されるステータスは 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のステータス; ID が無効であるか、無効なオプションが指定されている場合、失敗します。

別の解決策は、すべての pid を取得しwait、これらすべての pid に a を配置することです。

于 2013-11-03T17:25:40.933 に答える