Handle a signal: Difference between revisions
Content added Content deleted
(add erlang (escript) implementation) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 29:
Ada signal handlers must be defined at the library level.
The following package defines a simple signal handler for the SigInt signal.
<
with Ada.Interrupts.Names; use Ada.Interrupts.Names;
Line 42:
end Handler;
end Sigint_Handler;</
<
-------------
Line 71:
end Handler;
end Sigint_Handler;</
A signal may be received at any time in a program. Ada signal handling requires a task to suspend on an entry call for the handler which is executed only when the signal has been received. The following program uses the interrupt handler defined above to deal with receipt of SigInt.
<
with Ada.Text_Io; use Ada.Text_Io;
with Sigint_Handler; use Sigint_Handler;
Line 109:
null;
end Signals;</
{{out}}
<pre>
Line 124:
=={{header|AutoHotkey}}==
<
counter=0
SetTimer, timer, 500
Line 138:
Send, % "Task took " (A_TickCount-Start)/1000 " Seconds"
ExitApp
return</
{{out}}
<pre>1
Line 149:
=={{header|BaCon}}==
<
SUB Finished
SIGNAL SIG_DFL, SIGINT : ' Restore SIGINT to default
Line 162:
PRINT iter
iter = iter + 1
WEND</
{{out}}
Line 175:
This program runs only in console mode;
it must be compiled and then run as an EXE.
<
INSTALL @lib$+"CALLBACK"
CTRL_C_EVENT = 0
Line 207:
WHEN CTRL_C_EVENT: CtrlC% = TRUE : = 1
ENDCASE
= 0</
{{out}}
<pre>
Line 226:
Standard C's sleep() only provides one-second resolution, so the POSIX usleep() function is used here. (POSIX is not needed for the actual signal handling part.)
<
#include <stdlib.h> // for exit()
#include <signal.h>
Line 258:
printf("Program has run for %5.3f seconds\n", td);
return 0;
}</
{{out}}
Line 271:
Signals in C# are called events, and are handled by attaching event handler functions to the event, which are called when the event is triggered.
<
class Program
{
Line 293:
Environment.Exit(0);
}
}</
=={{header|C++}}==
{{trans|C}}
<
#include <csignal>
#include <ctime>
Line 329:
return 0;
}</
=={{header|Clojure}}==
Line 335:
<tt>(= (- Java verbosity) Clojure)</tt>
<
(def start (System/nanoTime))
Line 349:
(doseq [i (range)]
(prn i)
(Thread/sleep 500))</
=={{header|COBOL}}==
Works with GnuCOBOL 2.0
<
identification division.
program-id. signals.
Line 398:
goback.
end program handle-sigint.
</syntaxhighlight>
{{out}}
Line 416:
The full list of signal number can be found on [https://en.wikipedia.org/wiki/Unix_signal#POSIX_signals].
Tested on SBCL 1.2.7 and ECL 13.5.1.
<
(ql:quickload :cffi)
Line 439:
(format t "~a~&" (incf i))
(sleep 0.5)))
</syntaxhighlight>
{{out}}
Line 457:
=={{header|Crystal}}==
<
ch = Channel(Int32 | Symbol).new
Line 480:
elapsed = Time.utc - start
puts "Program has run for %5.3f seconds." % elapsed.total_seconds</
<pre>
Line 493:
=={{header|D}}==
{{trans|C}}
<
import core.thread;
import std.concurrency;
Line 521:
auto td = sw.peek();
writeln("Program has run for ", td);
}</
{{out}}
<pre>1
Line 536:
=={{header|Erlang|escript}}==
<
main([]) ->
Line 558:
timer:sleep(500),
output_loop(N + 1).
</syntaxhighlight>
=={{header|F_Sharp|F#}}==
<
let rec loop n = Console.WriteLine( n:int )
Line 575:
loop 1
main()</
=={{header|Forth}}==
Line 582:
Normally Gforth handles most signals (e.g., the user interrupt SIGINT, or the segmentation violation SIGSEGV) by translating it into a Forth THROW.
<
: numbers ( n -- n' )
Line 596:
<# # # # # # # [char] . hold #s #> type ." seconds" ;
main bye</
=={{header|FreeBASIC}}==
<
start = Timer
Line 617:
End If
Loop
</syntaxhighlight>
=={{header|Gambas}}==
<
fTime As Float
Line 651:
fTime += 0.5
End</
Output:
<pre>
Line 670:
=={{header|Go}}==
<
import (
Line 697:
}
}
}</
{{out}}
<pre>
Line 709:
=={{header|Haskell}}==
<
import Control.Exception (catch, throwIO, AsyncException(UserInterrupt))
import Data.Time.Clock (getCurrentTime, diffUTCTime)
Line 723:
loop i = do print i
threadDelay 500000 {- µs -}
loop (i + 1)</
=={{header|HicEst}}==
Subroutines "F2" to "F9" can be called any time by the F2...F9 keys or by a mouse click on the toolbar buttons "F2" to "F9". These buttons appear as soon as a SUBROUTINE "F2" to "F9" statement is compiled:
<
DO i = 1, 1E100 ! "forever"
Line 738:
WRITE(Messagebox, Name) seconds
ALARM(999) ! quit immediately
END</
==Icon and {{header|Unicon}}==
Line 744:
The following works in Unicon. I don't know if it works in Icon.
<
procedure main()
Line 754:
procedure handler(s)
stop("\n",&now-startTime," seconds")
end</
Sample run:
Line 772:
Use of sun.misc.SignalHandler allows one to specify which signal to catch, though is unsupported and potentially not available in all JVMs
<
import sun.misc.SignalHandler;
Line 791:
}
}
</syntaxhighlight>
Or one can use a generic shutdown hook as follows, though a reference to the particular signal is not available.
<
public static void main(String... args) throws InterruptedException {
final long start = System.nanoTime();
Line 810:
}
}
</syntaxhighlight>
{{out}}
<pre>
Line 828:
=={{header|JavaScript}}==
Based on NodeJS interpreter/engine
<
var count=0
secs=0
Line 844:
});
})();
</syntaxhighlight>
{{out}}
<pre>
Line 861:
=={{header|Jsish}}==
<
var gotime = strptime();
Line 878:
puts(loops++);
Event.update(500);
}</
''Event.update(500)'' causes the event loop to be monitored for 500 milliseconds, sleeping when there are no events to process for the given interval. 0 would return immediately.
Line 895:
=={{header|Julia}}==
<syntaxhighlight lang="julia">
ccall(:jl_exit_on_sigint, Cvoid, (Cint,), 0)
Line 912:
@time timeit()
println("Done.")
</syntaxhighlight>
The tricky bit for this task is the <code>ccall</code>, which tells the <code>main()</code> running Julia to pass SIGINT on to Julia as an error. This call is not needed when running this code in Julia's REPL, which has the desired behavior by default.
{{out}}
Line 932:
=={{header|Kotlin}}==
<
import sun.misc.Signal
Line 953:
Thread.sleep(500)
}
}</
Sample output:
Line 974:
=={{header|Liberty BASIC}}==
Liberty BASIC cannot react to a SigInt signal and truly kill itself. The best it can do is respond to Ctrl-C by exiting normally.
<syntaxhighlight lang="lb">
nomainwin
WindowHeight=DisplayHeight
Line 1,004:
if sigCtrl=1 and Inkey$=chr$(3) then sigInt=1
wait
</
=={{header|MATLAB}}==
MATLAB versions 6.5 (R13) and newer can no longer catch CTRL+C with a try-catch block. The onCleanup() function was introduced in version 7.6 (R2008a), possibly specifically for this situation. However, the designated onCleanup() function will execute no matter how the function ends (task completion, CTRL+C, exception), and CTRL+C will still cause an exception to be thrown and displayed.
{{works with|MATLAB|7.6 (R2008a) and later}}
<
k = 1;
tic
Line 1,018:
k = k+1;
end
end</
{{out}}
<pre>>> sigintCleanup
Line 1,031:
{{works with|MATLAB|6.1 (R12.1) and earlier}}
{{untested|MATLAB}}
<
k = 1;
tic
Line 1,044:
rethrow me
end
end</
=={{header|NewLISP}}==
<
(setq start-time (now))
Line 1,058:
(while (println (++ i))
(sleep 500))</
=={{header|Nim}}==
<
let t = epochTime()
Line 1,073:
for n in 1 ..< int64.high:
sleep 500
echo n</
Or if you prefer an exception to be thrown on SIGINT:
<
type EKeyboardInterrupt = object of CatchableError
Line 1,091:
echo n
except EKeyboardInterrupt:
echo "Program has run for ", formatFloat(epochTime() - t, precision = 0), " seconds."</
=={{header|OCaml}}==
OCaml's <tt>Unix.sleep</tt> doesn't handle non-integral arguments, so this program prints a number every second.
<
let start = Unix.gettimeofday ();;
Line 1,111:
loop (n + 1)
in
loop 1;;</
=={{header|Perl}}==
Before version 5.8 <tt>sleep</tt> requires an integer argument, so we'll spin (There exist more obtuse methods)
<
my $start = time; # seconds since epohc
my $arlm=5; # every 5 seconds show how we're doing
Line 1,137:
print ( ++$i," \n");
}</
^C to inerrupt, ^\ to quit, takes a break at 5 seconds
1
Line 1,171:
This example does the required task:
<
use AnyEvent;
my $start = AE::time;
Line 1,179:
my $num = AE::timer 0, 0.5, sub { say $n++ };
$exit->recv;
say " interrupted after ", AE::time - $start, " seconds";</
{{out}}
Line 1,200:
See builtins\pbreak.e for the low-level (inline assembly) cross platform signal handler,
and implementation of the standard hll allow_break() and check_break() routines
<!--<
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span>
<span style="color: #7060A8;">allow_break</span><span style="color: #0000FF;">(</span><span style="color: #004600;">false</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- by default Ctrl C terminates the program</span>
Line 1,213:
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"The program has run for %3.2f seconds\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">time</span><span style="color: #0000FF;">()-</span><span style="color: #000000;">t</span><span style="color: #0000FF;">})</span>
<!--</
{{out}}
<pre>
Line 1,225:
=={{header|PHP}}==
{{trans|Perl}}
<
declare(ticks = 1);
Line 1,241:
for ($n = 0; ; usleep(500000)) // 0.5 seconds
echo ++$n, "\n";
?></
=={{header|PicoLisp}}==
Put the following into a file, set it to executable, and run it
<
(push '*Bye '(println (*/ (usec) 1000000)) '(prinl))
Line 1,252:
(loop
(println (inc 'Cnt))
(wait 500) ) )</
=={{header|PL/I}}==
<syntaxhighlight lang="text">
handler: procedure options (main);
declare i fixed binary (31);
Line 1,271:
end;
end handler;
</syntaxhighlight>
=={{header|PowerShell}}==
<
$Start_Time = (Get-date).second
Write-Host "Type CTRL-C to Terminate..."
Line 1,293:
Write-Host "Total time in seconds"$Time_Diff
}
</syntaxhighlight>
{{Out}}
Line 1,309:
=={{header|PureBasic}}==
This code is for Windows only due to the usage of SetConsoleCtrlHandler()
<
CompilerError "This code is Windows only"
CompilerEndIf
Line 1,330:
PrintN("Program has run for "+StrF((T1-T0)/1000,3)+" seconds.")
Print ("Press ENTER to exit."):Input(): i=0
EndIf</
<pre>0
1
Line 1,341:
=={{header|Python}}==
Simple version
<
def counter():
Line 1,355:
break
counter()</
The following example should work on all platforms.
<
def intrptWIN():
Line 1,374:
intrptWIN()
tdelt = time.time() - t1
print 'Program has run for %5.3f seconds.' % tdelt</
There is a signal module in the standard distribution
that accomodates the UNIX type signal mechanism.
However the pause() mechanism is not implemented on Windows versions.
<
done = False
n = 0
Line 1,407:
intrptUNIX()
tdelt = time.time() - t1
print 'Program has run for %5.3f seconds.' % tdelt</
How about this one? It should work on all platforms;
and it does show how to install a signal handler:
<
class WeAreDoneException(Exception):
Line 1,433:
tdelt = time.time() - t1
print 'Program has run for %5.3f seconds.' % tdelt</
=={{header|Racket}}==
<
#lang racket
(define now current-milliseconds)
Line 1,447:
(displayln i)
(sleep 0.5)))
</syntaxhighlight>
{{out}}
<
0
1
Line 1,459:
7
Total time: 3.965
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
We note with glee that the task does not require us to print <em>consecutive</em> integers, so we'll print Fibonacci numbers instead. <tt>:-)</tt>
<syntaxhighlight lang="raku"
note "Took { now - INIT now } seconds.";
exit;
Line 1,472:
sleep 0.5;
.say;
}</
{{out}}
<pre>0
Line 1,495:
<br>But, there's more than one way to skin a cat. (No offense to cat lovers.)
<
/*────────────────────────────────── seconds that have elapsed since start of execution.*/
call time 'Reset' /*reset the REXX elapsed timer. */
Line 1,509:
halt: say 'program HALTed, it ran for' format(time("ELapsed"),,2) 'seconds.'
/*stick a fork in it, we're all done. */</
'''output'''
<pre>
Line 1,547:
=={{header|Ruby}}==
<
catch :done do
Line 1,563:
tdelt = Time.now - t1
puts 'Program has run for %5.3f seconds.' % tdelt</
=={{header|Rust}}==
<
#[cfg(unix)]
fn main() {
Line 1,626:
}
</syntaxhighlight>
=={{header|Scala}}==
{{libheader|Scala}}
<
import sun.misc.SignalHandler
Line 1,650:
Thread.sleep(500)
}
}</
=={{header|Sidef}}==
<
Sig.INT { |_|
Line 1,663:
Sys.say(i);
Sys.sleep(0.5);
} * Math.inf;</
{{out}}
Line 1,675:
=={{header|Smalltalk}}==
{{works with|Smalltalk/X}}<
n := 0.
Line 1,685:
Delay waitForSeconds: 0.5.
]
]</
or:
<
attaching an OS-signal (unix signal) to an exception or signal instance:
<
mySignal := Signal new mayProceed: false.
OperatingSytem operatingSystemSignal: (OperatingSystem signalNamed:'SIGHUP') install: mySignal.
Line 1,697:
] on: mySignal do:[
... handle SIGHUP gracefully...
]</
As the runtime system already catches common unix signals
and arranges for an OSError to be raised,
Line 1,705:
=={{header|Swift}}==
{{trans|C}}
<
let startTime = NSDate()
Line 1,722:
print("Program has run for \(endTime.timeIntervalSinceDate(startTime)) seconds")
</syntaxhighlight>
=={{header|Tcl}}==
Line 1,729:
Using Expect:
<
proc sigint_handler {} {
Line 1,744:
puts [incr n]
after 500
}</
Similarly, with TclX:
<
proc sigint_handler {} {
Line 1,762:
puts [incr n]
after 500
}</
With TclX, you don't have to trap signals,
you can convert the signal into a catchable error:
<
signal error sigint
Line 1,785:
puts "infinite loop interrupted, but not on SIGINT: $::errorInfo"
}
}</
With Tcl 8.6, that would be written as:
<
signal error sigint
Line 1,803:
} trap {POSIX SIG SIGINT} {} {
puts "elapsed time: [expr {[clock seconds] - $start_time}] seconds"
}</
Note also that from 8.5 onwards, Tcl also has other mechanisms for delivering interrupt-like things, such as interpreter resource limits which permit stopping an execution after a set amount of time and returning control to a supervisor module. However, this is not driven by user interrupts and is so only tangential to ''this'' task.
Line 1,809:
=={{header|TXR}}==
<
(lambda (signum async-p)
(throwf 'error "caught signal ~s" signum)))
Line 1,820:
(let ((end-time (time)))
(format t "\n\n~a after ~s seconds of execution\n"
msg (- end-time start-time))))))</
{{out|Run}}
Line 1,850:
that signals the shell every half a second.
<
# Trap signals for SIGQUIT (3), SIGABRT (6) and SIGTERM (15)
trap "echo -n 'We ran for ';echo -n `expr $c /2`; echo " seconds"; exit" 3 6 15
Line 1,856:
# wait 0.5 # We need a helper program for the half second interval
c=`expr $c + 1`
done</
{{works with|bash}}
Note that the following solution only works on systems
that support a version of sleep that can handle non-integers.
<
#!/bin/bash
trap 'echo "Run for $((s/2)) seconds"; exit' 2
Line 1,872:
let s++
done
</syntaxhighlight>
{{out}}
Line 1,890:
with a 5 tenths of a second timeout:
<
trap 'echo "Run for $((s/2)) seconds"; exit' 2
s=1
Line 1,908:
half_sec_sleep
let s++
done</
{{works with|zsh}}
<
for (( n = 0; ; n++)) sleep 1</
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<
Dim startTime As Date
Line 1,938:
End Sub
End Module</
=={{header|Visual FoxPro}}==
<
*!* In VFP, Ctrl+C is normally used to copy text to the clipboard.
*!* Esc is used to stop execution.
Line 1,965:
lLoop = .F.
ENDPROC
</syntaxhighlight>
=={{header|Wren}}==
Note that Thread.sleep not only suspends the current fiber but also the System.clock method (possibly unintended). We therefore have to add back on the time slept.
<
import "timer" for Timer
import "io" for Stdin
Line 1,996:
}
Stdin.isRaw = false
stop = true</
{{out}}
Line 2,022:
It is entirely possible to do this entirely in syscalls using sys_nanosleep/sys_write but that would require allot more work,
definition of the timespec structure among other things.
<
%define sys_signal 48
%define SIGINT 2
Line 2,076:
start_time resd 1
end_time resd 1
</syntaxhighlight>
=={{header|zkl}}==
SigInt is the only signal zkl brings out.
<
try{ n:=0; while(1){(n+=1).println(); Atomic.sleep(0.5)} }
catch{ println("ran for ",Time.Clock.time-t," seconds"); System.exit() }</
{{out}}
<pre>
|