Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ctrl+c to kill a bash script with child processes

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?

like image 474
18446744073709551615 Avatar asked Jul 09 '15 10:07

18446744073709551615


People also ask

Does Ctrl C kill process?

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.

How Ctrl C works in Bash?

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.

How do I stop a bash script execution?

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.

How do I kill a program in Bash?

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.


Video Answer


1 Answers

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
like image 155
oz123 Avatar answered Sep 25 '22 21:09

oz123