シェルスクリプトが眠っている間、外部からどのように制御できますか?

シェルスクリプトが眠っている間、外部からどのように制御できますか?

私はシェルスクリプトに初めて触れました。次のようなスクリプトがあります。

while [ true ]
do
  sleep 5m
  # PART X: code that executes every 5 mins
done

実行中に(1)外部からプログラムを傍受し、(2)眠っているプロセスを停止し、すぐにパートXを実行する方法は?これを達成するためにSIGNALSを使用できますか?それとももっと良い方法がありますか?

この種の問題を解決する一般的な方向を教えてください。

ベストアンサー1

処理時間はスクリプトの責任です。これが今日使用するためのものであっても、/bin/sleep将来は使用されない可能性があるため、実際に長期的に動作するという保証はありません。わかった 君が見たいできるそのような保証をしないでください。私のポイントは、スリープが実装の詳細なので、スクリプトの外部で直接スリープを終了してはいけません。代わりに、スクリプトが別の信号をキャプチャしてSIGUSR1スクリプトに送信するようにしてください。

簡単な例は次のとおりです。

#!/usr/bin/env bash

kill_the_sleeper () {
    # This probably isn't really needed here
    # If we don't kill the sleep process, it'll just
    # hang around in the background until it finishes on its own
    # which isn't much of an issue for "sleep" in particular
    # But cleaning up after ourselves is good practice, so let's
    # Just in case we end up doing something more complicated in future
    if [ -v sleep_pid ]; then
        kill "$sleep_pid"
    fi
}

trap kill_the_sleeper USR1 EXIT

while true; do
    # Signals don't interrupt foreground jobs,
    # but they do interrupt "wait"
    # so we "sleep" as a background job
    sleep 5m &
    # We remember its PID so we can clean it up
    sleep_pid="$!"
    # Wait for the sleep to finish or someone to interrupt us
    wait
    # At this point, the sleep process is dead (either it finished, or we killed it)
    unset sleep_pid

    # PART X: code that executes every 5 mins
done

それからあなたは引き起こす可能性がありますパート10走るkill -USR1 "$pid_of_the_script"pkill -USR1 -f my_fancy_script

このスクリプトは完璧とにかく、しかし、少なくとも単純な場合は良いでしょう。

おすすめ記事