Oct 212008
Just a little ditty … Let’s say you wanted a process to block infinitely, without using much CPU, and producing continous, non-buffered output? Try this:
inf.pl:
#!/usr/bin/perl my $timeout = $ARGV[0]; if ((defined $timeout) && ($timeout > 0)) { $timeout = time() + $timeout; } else { $timeout = 0; } my $k = 0; $SIG{INT} = \&caught_int; sub caught_int { $SIG{INT} = 'DEFAULT'; print "\nCaptured SIGINT. Exiting after $k seconds.\n"; #die; exit; } $| = 1; while (!$timeout || (time() < $timeout)) { $k++; print "$k\n"; sleep 1; }
Running this program with default yields an infinite stream of numbers with output every second, until you press Control-C, like so:
$ inf.pl 1 2 3 4 5 6 7 8 9 10 11 ^C Captured SIGINT. Exiting after 11 seconds.
If a numerical argument is provided, then output is generated for that number of seconds, and then the program exits, like so:
$ inf.pl 3 1 2 3
It’s a simple Perl script that demonstrates simple command-line argument parsing, catching Control-C (interrupts), watching the clock, and producing steady output with minimal CPU usage. … Plus, it comes in handy while testing other, more complex Perl scripts.