Handle a signal: Difference between revisions
Content added Content deleted
(Add SIGQUIT since per the task description SIGQUIT is more appropriate that SIGINT (see perl example) see discussion.) |
(demonstrate the power or signal handling) |
||
Line 827: | Line 827: | ||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
Before version 5.8 <tt>sleep</tt> requires an integer argument, so we'll spin (There exist more obtuse methods) |
|||
Perl's (in fact Unix's) <tt>sleep</tt> doesn't handle non-integral arguments correctly on some platforms, so this program uses the select syscall for timeout. |
|||
<lang perl> |
<lang perl> |
||
my $start = time; # seconds since epohc |
|||
my $arlm=5; # every 5 seconds show how we're doing |
|||
my $i; |
|||
$SIG{QUIT} = sub |
|||
{print " Ran for ", time - $start, " seconds.\n"; die; }; |
|||
$SIG{INT} = sub |
$SIG{INT} = sub |
||
{print |
{print " Running for ", time - $start, " seconds.\n"; }; |
||
$SIG{ALRM} = sub |
|||
exit;}; |
|||
{print " After $arlm seconds i= $i. Executing for ", time - $start, " seconds.\n"; alarm $arlm }; |
|||
alarm $arlm; # trigger ALaRM after we've run for a while |
|||
print " ^C to inerrupt, ^\\ to quit, takes a break at $arlm seconds \n"; |
|||
while ( 1 ) { |
|||
for ( $w=11935000; $w--; $w>0 ){}; # spinning is bad, but hey it's only a demo |
|||
⚫ | |||
} |
|||
^C to inerrupt, ^\ to quit, takes a break at 5 seconds |
|||
1 |
|||
2 |
|||
^C Running for 1 seconds. |
|||
3 |
|||
4 |
|||
^C Running for 2 seconds. |
|||
5 |
|||
6 |
|||
7 |
|||
^C Running for 3 seconds. |
|||
8 |
|||
9 |
|||
10 |
|||
After 5 seconds i= 10. Executing for 5 seconds. |
|||
11 |
|||
12 |
|||
13 |
|||
14 |
|||
15 |
|||
16 |
|||
17 |
|||
18 |
|||
19 |
|||
20 |
|||
After 5 seconds i= 20. Executing for 10 seconds. |
|||
21 |
|||
22 |
|||
^\ Ran for 11 seconds. |
|||
Died at 0.pl line 6.. |
|||
for (my $n = 0 ;; select(undef, undef, undef, .5)) |
|||
⚫ | |||
This example does the required task: |
This example does the required task: |