I have a script whose internals boil down to:
trap "exit" SIGINT SIGTERM
while :
do
mplayer sound.mp3
sleep 3
done
(yes, it is a bit more meaningful than the above, but that's not relevant to the problem). Several instances of the script may be running at the same time.
Sometimes I want to ^C the script... but that does not succeed. As I understand, when ^C kills mplayer
, it continues to sleep
, and when ^C kills sleep
, it continues to mplayer
, and I never happen to catch it in between. As I understand, trap
just never works.
How do I terminate the script?
Turned out the way Ctrl-c works is quite simple — it's just a shortcut key for sending the interrupt (terminate) signal SIGINT to the current process running in the foreground. Once the process gets that signal, it's terminating itself and returns the user to the shell prompt.
When you hit Ctrl + c , the line discipline of your terminal sends SIGINT to processes in the foreground process group. Bash, when job control is disabled, runs everything in the same process group as the bash process itself.
If you are executing a Bash script in your terminal and need to stop it before it exits on its own, you can use the Ctrl + C combination on your keyboard.
On Unix-like operating systems, kill is a builtin command of the Bash shell. It sends a signal to a process. This page covers the bash builtin version of kill, which is distinct from the standalone binary executable, /bin/kill. To figure out which of these is the default kill on your system, run type kill.
You can get the PID of mplayer
and upon trapping send the kill signal to mplayer's PID.
function clean_up {
# Perform program exit housekeeping
KILL $MPLAYER_PID
exit
}
trap clean_up SIGHUP SIGINT SIGTERM
mplayer sound.mp3 &
MPLAYER_PID=$!
wait $MPLAYER_PID
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With