ループを含むスクリプトを作成しましたuntil
。ループは、true
ブール変数がループの外側に設定されるまで実行する必要があります。残念ながら、ループは変数がtrueに設定されていることを無視して実行され続けます。この問題を引き起こす行は次のとおりです。
boolean=false
{ sleep 5 && boolean=true && echo "boolean is true now" ; } &
{ until [ "$boolean" = true ] ; do sleep 1 && echo $boolean ; done ; } &&
echo "boolean is true now: $boolean"
生成された出力は次のとおりです。
false
false
false
false
boolean is true now
false
false
false
...
boolean
に設定されている場合、ループを終了するにはどうすればよいですかtrue
?
ベストアンサー1
信号は、前景シェルと背景シェルとの間の通信に使用することができる。
#!/bin/bash
# global variable for foreground shell
boolean=false
# register a signal handler for SIGUSR1
trap handler USR1
# the handler sets the global variable
handler() { boolean=true; }
echo "before: $boolean"
# Here, "$$" is the pid of the foreground shell
{ sleep 5; kill -USR1 $$; echo "finished background process"; } &
# busy waiting
until $boolean; do
echo "waiting..."
sleep 1
done
echo "after: $boolean"
出力
before: false
waiting...
waiting...
waiting...
waiting...
waiting...
finished background process
after: true