6

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?

oz123
  • 27,559
  • 27
  • 125
  • 187
18446744073709551615
  • 16,368
  • 4
  • 94
  • 127
  • Well-behaved applications that exit on SIGINT should kill itself with SIGINT to let the caller respond too. See http://mywiki.wooledge.org/SignalTrap#Special_Note_On_SIGINT . `sleep` should behave, hopefully `mplayer` does too. – Etan Reisner Jul 09 '15 at 13:17

2 Answers2

6

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
oz123
  • 27,559
  • 27
  • 125
  • 187
1

mplayer returns 1 when it is stopped with Ctrl-C so:

mplayer sound.mp3 || break

will do the work.

One issue of this method is that if mplayer exits 1 for another reason (i.e., sound file has a bad format), it will exit anyway, and it's maybe not the desired behaviour.

yolenoyer
  • 8,797
  • 2
  • 27
  • 61
  • Sorry I'm not sure to understand what you mean. I thought the problem was that ctrl-c was trapped by mplayer, and did never terminate the fatherprocess..? – yolenoyer Jul 09 '15 at 10:55
  • I read it again comprehensively and now i see that he is no able to terminate the fatherprocess.. so everything is fine – Noli Jul 09 '15 at 10:59
  • However, Oz123's answer is a more elegant solution – yolenoyer Jul 09 '15 at 11:05
  • As I understand, in case of a read error it will also terminate with a non-zero code, and such termination is what the script is intended to handle. Unfortunately, I cannot find any docs on mplayer return codes and reasons. – 18446744073709551615 Jul 09 '15 at 12:45