5

次のようなbashスクリプトがあります。

#!/bin/bash
startsomeservice &
echo $! > service.pid

while true; do
    # dosomething in repeat all the time here
    foo bar
    sleep 5
done

# cleanup stuff on abort here
rm tmpfiles
kill $(cat service.pid)

このスクリプトの問題は、中止できないことです。ctrl+ci を押すと、次のループに入ります...このようなスクリプトを実行することは可能ですが、中止可能にすることはできますか?

4

4 に答える 4

6

Since you are executing the script with Bash, you can do the following:

#!/bin/bash

startsomeservice &
echo $! > service.pid

finish()
{
    rm tmpfiles
    kill $(cat service.pid)
    exit
}
trap finish SIGINT

while :; do
    foo bar
    sleep 5
done

Please note that this behaviour is Bash specific, if you run it with Dash, for instance, you will see two differences:

  1. You cannot capture SIGINT
  2. The interrupt signal will break the shell loop.

Note also that you will break a shell loop with a single C-c when you execute the loop directly from an interactive prompt, even if you're running Bash. See this detailed discussion about SIGINT handling from shells.

于 2012-06-12T09:34:44.087 に答える