[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Protect Loop Execution with Traps

From: Greg Wooledge
Subject: Re: Protect Loop Execution with Traps
Date: Tue, 28 Jan 2020 16:07:21 -0500
User-agent: Mutt/1.10.1 (2018-07-13)

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

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.

trap exit INT
while true; do
  ping -c 3

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:

trap 'trap INT; kill -INT $$' INT
while true; do
  ping -c 3

reply via email to

[Prev in Thread] Current Thread [Next in Thread]