
ファイルを生成するプロセスが実行中です。
clean_db () {
while read i
do
Some_long_process >> output.txt
done < input_db
別のプロセスを実行し、生成された行数を計算したいと思います。正常に動作します。
while true
do
wc -l output.txt | awk '{ print $1 }'
sleep 5
done
}
ただし、最初のプロセスが終了すると、2番目のプロセスを停止できず、1番目のプロセスが終了しても2番目のプロセスは機能し続けます。最初のものが終わったら、2番目のものを最初に接続して停止するにはどうすればよいですか?
答え1
2番目の機能はバックグラウンドサブプロセスで始まり、シェルスクリプトを終了するとすべてのサブプロセスが終了します。
second_process () {
while true
do
wc -l output.txt
sleep 1
done
}
clean_db () {
second_process &
for i in $(seq 5);
do
echo "kfjdjkfdf" >> output.txt
echo "Done adding" $i
sleep 1
done
}
clean_db
pkill -P $$
これにより、pkill -P $$
すべての子プロセスが終了します。
答え2
最終的な完全な解決策は次のとおりです。
Check_process () {
while true
do
wc -l output.txt | awk '{ print $1 }'
sleep 5
done
}
clean_db () {
# The following sets build in bash trap for Ctrl+C and kills background process when Ctrl+C is detected
trap 'kill $BGPID; exit' INT
Check_process &
BGPID=$!
while read i
do
Some_long_process >> output.txt
done < input_db
}
clean_db