シェルスクリプトはバックグラウンドコマンドを待ちます。

シェルスクリプトはバックグラウンドコマンドを待ちます。

スクリプトを書いていますが、何かが必要ですが、方法が見つかりません...

バックグラウンド「command1&」からコマンドを生成し、コマンド2を実行する前に、スクリプトのどこかでコマンドが完了するまで待つ必要があります。デフォルトでは、以下が必要です。

注:各コマンドは特定のディレクトリで実行されます! whileループが終わると、私のcommand1はそれぞれ特定のプロセスを実行する4つのディレクトリを作成するため、実行されるプロセスの総数は4つです。

a=1

while [$a -lt 4 ]

     . command1
   #Generates 1 Process  

     a= `export $a +1`
done

   #Wait until the 4 process end and then run the command2 

    . command2

pidプロセス番号を含むコマンドの内容を見たことがありますが、waitそれも機能しません。

ベストアンサー1

wait PIDこのコマンドを使用して、プロセスが終了するのを待つことができます。

次のコマンドを使用して、最後のコマンドのPIDを取得することもできます。$!

あなたの場合は、次のように動作します。

command1 & #run command1 in background
PID=$! #catch the last PID, here from command1
command2 #run command2 while command1 is running in background
wait $PID #wait for command1, in background, to end
command3 #execute once command1 ended

編集後は複数のPIDがあり、それを知っているので、次のことができます。

command1 & #run command1 in background
PID1=xxxxx
PID2=yyyyy
PID3=xxyyy
PID4=yyxxx
command2 #run command2 while command1 is running in background
wait $PID1 $PID2 $PID3 $PID4 #wait for the four processes of command1, in background, to end
command3 #execute once command1 ended

おすすめ記事