Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > gnu.bash.bug > #15830 > unrolled thread

Re: Protect Loop Execution with Traps

Started byGreg Wooledge <wooledg@eeg.ccf.org>
First post2020-01-28 16:07 -0500
Last post2020-01-28 16:07 -0500
Articles 1 — 1 participant

Back to article view | Back to gnu.bash.bug

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Protect Loop Execution with Traps Greg Wooledge <wooledg@eeg.ccf.org> - 2020-01-28 16:07 -0500

#15830 — Re: Protect Loop Execution with Traps

FromGreg Wooledge <wooledg@eeg.ccf.org>
Date2020-01-28 16:07 -0500
SubjectRe: Protect Loop Execution with Traps
Message-ID<mailman.264.1580245673.2185.bug-bash@gnu.org>
On Tue, Jan 28, 2020 at 03:49:32PM -0500, Roger wrote:
> As I slept on this, I realized the likeliness some programs are also trapping 
> CTRL-C as you just explained.
> 
> The programs I'm using within a loop were ffmpeg && mv (rename) after verifying 
> ffmpeg created a file >0 bytes.

I'm not familiar with ffmpeg in detail.  An ffmpeg mailing list might
be able to offer more focused advice.

> But as I re-think think this, should be good Bash scripting practice to 
> integrate a trap within each loop? 

That doesn't sound right.  Let me go back to my previous example using
ping.

Let's say that for reasons outside the scope of bug-bash, you're forced
to perform a ping in a loop.  And that you will almost certainly want
to abandon the loop prematurely using Ctrl-C.  And that you aren't allowed
to fix the misbehaving ping command at the source code level.

Here's a simple fix, that involves setting up ONE trap within the
shell script, to override the shell's default SIGINT handling heuristic.


#!/bin/bash
trap exit INT
while true; do
  ping -c 3 8.8.8.8
done


There.  Now, when I hit Ctrl-C, the whole script exits, not just one
instance of ping.

(Switching from -c 1 to -c 3 made it a *lot* less spammy, and also much
harder to kill using the "press Ctrl-C twice really fast" approach.
The INT trap works around it beautifully for me, though.)

Whether this same stuff applies to ffmpeg, I have no idea.  I also
don't know why you're Ctrl-C'ing out of an ffmpeg loop often enough
that this has become a concern.

But, the "simple fix" that I used here has the same issue that ping
itself has -- we're catching SIGINT and handling it and exiting,
instead of letting SIGINT kill us.  If something runs *us* in a loop,
it'll have the same problem that *we* had when we tried to run ping
in a loop.

So, in the interest of not causing problems for other programs, here's
the more correct fix:


#!/bin/bash
trap 'trap INT; kill -INT $$' INT
while true; do
  ping -c 3 8.8.8.8
done

[toc] | [standalone]


Back to top | Article view | gnu.bash.bug


csiph-web