0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

階層的なシェルスクリプトにおいて、childプロセスの終了を待つ

Posted at

shell scriptで3階層の入れ子状のスクリプトを走らせたい。
また、i番目のchild process の全ての処理が終了してから、(i+1)番目のchild processを行いたい。

ナイーブなイメージ1

'000_parent.sh'
sh child_100.sh
# child_100.shの全ての処理が終わるまで待つ。
sh child_200.sh
# child_200.shの全ての処理が終わるまで待つ。
'child_100.sh'
sh grandchild_101.sh
sh grandchild_102.sh
sh grandchild_103.sh
# 101-103は同時に実行されて良い。101-103が全て終わるまで待つ。
'child_200.sh'
sh grandchild_201.sh
sh grandchild_202.sh
sh grandchild_203.sh
# 201-203は同時に実行されて良い。201-203が全て終わるまで待つ。

実装例1 cdを伴わないシンプルな場合

'000_parent.sh'
(
  sh child_100.sh
) &
PID100=$!
wait $PID100

(
  sh child_200.sh
) &
PID200=$!
wait $PID200
'child_100.sh'
(
  sh grandchild_101.sh
) &
PID101=$!

(
  sh grandchild_102.sh
) &
PID102=$!

(
  sh grandchild_103.sh
) &
PID103=$!

wait $PID101 $PID102 $PID103
'child_200.sh'
(
  sh grandchild_201.sh
) &
PID201=$!

(
  sh grandchild_202.sh
) &
PID202=$!

(
  sh grandchild_203.sh
) &
PID203=$!

wait $PID201 $PID202 $PID203

実装

'child_100.sh'
(
  cd d1
  sh 3_script.sh
  cd ../
  exit 111
) &
PID1=$!
wait $PID1
echo $?

(
  cd d2
  sh 3_script.sh
  cd ../
  exit 222
) &
PID2=$!
wait $PID2
echo $?

ナイーブなイメージ2 (cd を伴う場合)

'000_parent.sh'
sh child_100.sh
# child_100.shの全ての処理が終わるまで待つ。

sh child_200.sh
# child_200.shの全ての処理が終わるまで待つ。
'child_100.sh'
cd directory_101
sh grandchild_101.sh

cd ../directory_102
sh grandchild_102.sh

cd ../directory_103
sh grandchild_103.sh
# 101-103は同時に実行されて良い。101-103が全て終わるまで待つ。
cd ../
'child_200.sh'
cd directory_201
sh grandchild_201.sh

cd ../directory_202
sh grandchild_202.sh

cd ../directory_203
sh grandchild_203.sh
# 201-203は同時に実行されて良い。201-203が全て終わるまで待つ。
cd ../

実装例2 cdを伴なう場合

'000_parent.sh'
(
  sh child_100.sh
) &
PID100=$!
wait $PID100

(
  sh child_200.sh
) &
PID200=$!
wait $PID200
'child_100.sh'
(
  cd directory_101
  sh grandchild_101.sh
) &
PID101=$!

(
  cd directory_102
  sh grandchild_102.sh
) &
PID102=$!

(
  cd directory_103
  sh grandchild_103.sh
) &
PID103=$!

wait $PID101 $PID102 $PID103
'child_200.sh'
(
  cd directory_201
  sh grandchild_201.sh
) &
PID201=$!

(
  cd directory_202
  sh grandchild_202.sh
) &
PID202=$!

(
  cd directory_203
  sh grandchild_203.sh
) &
PID203=$!

wait $PID201 $PID202 $PID203

参考
https://qiita.com/blueskyarea/items/f07466393ccb5efb3dc5

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?