Handle a signal: Difference between revisions

No edit summary
imported>Nmz
 
(43 intermediate revisions by 23 users not shown)
Line 1:
{{task|Concurrency}} {{requires|Signal handling}} [[Category:Signal handling]]
{{requires|Signal handling}}
[[Category:Signal handling]]
{{omit from|Erlang|Does not handle signals.}}
{{omit from|Batch File|"Pure" Batch files cannot really handle signals.}}
Line 12 ⟶ 14:
{{omit from|XSLT}}
 
Most general purpose operating systems provide interrupt facilities, sometimes called signals either generated by the user or as a result of program failure or reaching a limit like file space.
Unhandled signals generally terminate a program in a disorderly manner.
Signal handlers are created so that the program behaves in a well-defined manner upon receipt of a signal.
 
;Task:
For this task you will provide a program that displays a single integer
Provide a program that displays an integer on each line of output at the rate of about one integer in eachper half second.
<!-- some systems have difficulty with 1/2 second and that's not the point of this subject anyway DG-->
Upon receipt of the SigInt signal (often created by the user typing ctrl-C) the program will cease printing integers to its output, print the number of seconds
Upon receipt of the SIGINT signal (often generated by the user typing ctrl-C <!-- on unix see stty -a . on windows SIGBREAK DG -->( or better yet, SIGQUIT ctrl-\ )) the program will cease outputting integers, output the number of seconds the program has run, and then the program will quit. <!-- outputting the number if seconds is also unduly complicated for this topic . Hope nobody minds these comments and I didn't really want to change the task since there were so many examples already written. see the Perl example for a more extensive use of signals. PS See discussion. If you find these edits inappropriate let me know DG-->
the program has run, and then the program will terminate.
<br><br>
 
=={{header|Ada}}==
Line 26 ⟶ 29:
Ada signal handlers must be defined at the library level.
The following package defines a simple signal handler for the SigInt signal.
<langsyntaxhighlight lang="ada">with Ada.Interrupts; use Ada.Interrupts;
with Ada.Interrupts.Names; use Ada.Interrupts.Names;
 
Line 39 ⟶ 42:
end Handler;
 
end Sigint_Handler;</langsyntaxhighlight>
<langsyntaxhighlight lang="ada">package body Sigint_Handler is
 
-------------
Line 68 ⟶ 71:
end Handler;
 
end Sigint_Handler;</langsyntaxhighlight>
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.
<langsyntaxhighlight lang="ada">with Ada.Calendar; use Ada.Calendar;
with Ada.Text_Io; use Ada.Text_Io;
with Sigint_Handler; use Sigint_Handler;
Line 106 ⟶ 109:
null;
end Signals;</langsyntaxhighlight>
{{out}}
<pre>
Line 121 ⟶ 124:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">Start:=A_TickCount
counter=0
SetTimer, timer, 500
Line 135 ⟶ 138:
Send, % "Task took " (A_TickCount-Start)/1000 " Seconds"
ExitApp
return</langsyntaxhighlight>
{{out}}
<pre>1
Line 145 ⟶ 148:
Task took 3.526 Seconds</pre>
 
=={{header|Batch FileBaCon}}==
<syntaxhighlight lang="freebasic">' Handle signal
<pre>
SUB Finished
@echo off
SIGNAL SIG_DFL, SIGINT : ' Restore SIGINT to default
set IntEchoedTimes= 0
PRINT "Running for", TIMER / 1000.0, "seconds" FORMAT "%s %f %s\n"
echo X to send terminate signal
STOP SIGINT : ' Send another terminating SIGINT
:LoopStart
ENDSUB
set/a "IntEchoedTimes"= %IntEchoedTimes% + 1
 
choice /C 7X /N /T "1" /D 7
SIGNAL Finished, SIGINT
if %ERRORLEVEL% == 1 goto LoopStart
iter = 1
if %ERRORLEVEL% == 2 goto Terminate
WHILE TRUE
:Terminate
SLEEP 500
echo The program has been running for %IntEchoedTimes% seconds.
PRINT iter
echo Terminating...
iter = iter + 1
timeout /t 3 /nobreak >nul
WEND</syntaxhighlight>
exit
 
</pre>
{{out}}
<pre>$ ./handle-signal
1
2
3
^CRunning for 1.766000 seconds</pre>
 
=={{header|BBC BASIC}}==
Line 166 ⟶ 175:
This program runs only in console mode;
it must be compiled and then run as an EXE.
<langsyntaxhighlight lang="bbcbasic"> REM!Exefile C:\bbcsigint.exe,encrypt,console
INSTALL @lib$+"CALLBACK"
CTRL_C_EVENT = 0
Line 198 ⟶ 207:
WHEN CTRL_C_EVENT: CtrlC% = TRUE : = 1
ENDCASE
= 0</langsyntaxhighlight>
{{out}}
<pre>
Line 217 ⟶ 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.)
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <stdlib.h> // for exit()
#include <signal.h>
Line 249 ⟶ 258:
printf("Program has run for %5.3f seconds\n", td);
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 262 ⟶ 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.
 
<langsyntaxhighlight lang="csharp">using System; //DateTime, Console, Environment classes
class Program
{
Line 284 ⟶ 293:
Environment.Exit(0);
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
{{trans|C}}
<syntaxhighlight lang="cpp">#include <chrono>
#include <csignal>
#include <ctime>
#include <iostream>
#include <thread>
 
volatile sig_atomic_t gotint = 0;
 
void handler(int signum) {
// Set a flag for handling the signal, as other methods like printf are not safe here
gotint = 1;
}
 
int main() {
using namespace std;
 
signal(SIGINT, handler);
 
int i = 0;
clock_t startTime = clock();
while (true) {
if (gotint) break;
std::this_thread::sleep_for(std::chrono::milliseconds(500));
if (gotint) break;
cout << ++i << endl;
}
clock_t endTime = clock();
 
double dt = (endTime - startTime) / (double)CLOCKS_PER_SEC;
cout << "Program has run for " << dt << " seconds" << endl;
 
return 0;
}</syntaxhighlight>
 
=={{header|Clojure}}==
Line 290 ⟶ 335:
<tt>(= (- Java verbosity) Clojure)</tt>
 
<langsyntaxhighlight Clojurelang="clojure">(require 'clojure.repl)
 
(def start (System/nanoTime))
Line 304 ⟶ 349:
(doseq [i (range)]
(prn i)
(Thread/sleep 500))</langsyntaxhighlight>
 
=={{header|COBOL}}==
Works with GnuCOBOL 2.0
<syntaxhighlight lang="cobol">
identification division.
program-id. signals.
data division.
working-storage section.
01 signal-flag pic 9 external.
88 signalled value 1.
01 half-seconds usage binary-long.
01 start-time usage binary-c-long.
01 end-time usage binary-c-long.
01 handler usage program-pointer.
01 SIGINT constant as 2.
 
procedure division.
call "gettimeofday" using start-time null
set handler to entry "handle-sigint"
call "signal" using by value SIGINT by value handler
 
perform until exit
if signalled then exit perform end-if
call "CBL_OC_NANOSLEEP" using 500000000
if signalled then exit perform end-if
add 1 to half-seconds
display half-seconds
end-perform
 
call "gettimeofday" using end-time null
subtract start-time from end-time
display "Program ran for " end-time " seconds"
goback.
end program signals.
 
identification division.
program-id. handle-sigint.
data division.
working-storage section.
01 signal-flag pic 9 external.
 
linkage section.
01 the-signal usage binary-long.
 
procedure division using by value the-signal returning omitted.
move 1 to signal-flag
goback.
end program handle-sigint.
</syntaxhighlight>
 
{{out}}
<pre>
prompt$ cobc -x -j signals.cob
+0000000001
+0000000002
+0000000003
+0000000004
+0000000005
^CProgram ran for +00000000000000000002 seconds
prompt$
</pre>
 
=={{header|Common Lisp}}==
Line 310 ⟶ 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.
<langsyntaxhighlight lang="lisp">
(ql:quickload :cffi)
 
(defvardefconstant *+SIGINT*+ 2)
 
(defmacro set-signal-handler (signo &body body)
Line 325 ⟶ 431:
(defvar *initial* (get-internal-real-time))
 
(set-signal-handler *+SIGINT*+
(format t "Ran for ~a seconds~&" (/ (- (get-internal-real-time) *initial*) internal-time-units-per-second))
(quit))
Line 332 ⟶ 438:
(loop do
(format t "~a~&" (incf i))
(sleep 0.5)))
</syntaxhighlight>
)
)
 
</lang>
 
{{out}}
Line 352 ⟶ 455:
Ran for 4901/1000 seconds
</pre>
 
=={{header|Crystal}}==
<syntaxhighlight lang="ruby">start = Time.utc
ch = Channel(Int32 | Symbol).new
 
spawn do
i = 0
loop do
sleep 1
ch.send(i += 1)
end
end
 
Signal::INT.trap do
Signal::INT.reset
ch.send(:kill)
end
 
loop do
x = ch.receive
break if x == :kill
puts x
end
 
elapsed = Time.utc - start
puts "Program has run for %5.3f seconds." % elapsed.total_seconds</syntaxhighlight>
 
<pre>
1
2
3
4
5
^CProgram has run for 5.093 seconds.
</pre>
 
=={{header|D}}==
{{trans|C}}
<syntaxhighlight lang="d">import core.stdc.signal;
import core.thread;
import std.concurrency;
import std.datetime.stopwatch;
import std.stdio;
 
__gshared int gotint = 0;
extern(C) void handleSigint(int sig) nothrow @nogc @system {
/*
* Signal safety: It is not safe to call clock(), printf(),
* or exit() inside a signal handler. Instead, we set a flag.
*/
gotint = 1;
}
 
void main() {
auto sw = StopWatch(AutoStart.yes);
signal(SIGINT, &handleSigint);
for (int i=0; !gotint;) {
Thread.sleep(500_000.usecs);
if (gotint) {
break;
}
writeln(++i);
}
sw.stop();
auto td = sw.peek();
writeln("Program has run for ", td);
}</syntaxhighlight>
{{out}}
<pre>1
2
3
4
5
6
7
8
9
Program has run for 5 secs, 4 ms, 357 ╬╝s, and 4 hnsecs</pre>
 
=={{header|Erlang|escript}}==
 
<syntaxhighlight lang="erlang">#! /usr/bin/env escript
 
main([]) ->
erlang:unregister(erl_signal_server),
erlang:register(erl_signal_server, self()),
Start = seconds(),
os:set_signal(sigquit, handle),
Pid = spawn(fun() -> output_loop(1) end),
receive
{notify, sigquit} ->
erlang:exit(Pid, normal),
Seconds = seconds() - Start,
io:format("Program has run for ~b seconds~n", [Seconds])
end.
 
seconds() ->
calendar:datetime_to_gregorian_seconds({date(),time()}).
 
output_loop(N) ->
io:format("~b~n",[N]),
timer:sleep(500),
output_loop(N + 1).
</syntaxhighlight>
 
=={{header|F_Sharp|F#}}==
<syntaxhighlight lang="fsharp">open System
 
let rec loop n = Console.WriteLine( n:int )
Threading.Thread.Sleep( 500 )
loop (n + 1)
 
let main() =
let start = DateTime.Now
Console.CancelKeyPress.Add(
fun _ -> let span = DateTime.Now - start
printfn "Program has run for %.0f seconds" span.TotalSeconds
)
loop 1
 
main()</syntaxhighlight>
 
=={{header|Forth}}==
Line 358 ⟶ 582:
Normally Gforth handles most signals (e.g., the user interrupt SIGINT, or the segmentation violation SIGSEGV) by translating it into a Forth THROW.
 
<langsyntaxhighlight lang="forth">-28 constant SIGINT
 
: numbers ( n -- n' )
Line 372 ⟶ 596:
<# # # # # # # [char] . hold #s #> type ." seconds" ;
 
main bye</langsyntaxhighlight>
 
=={{header|F_Sharp|F#Fortran}}==
{{Works with|gfortran}}
<lang fsharp>open System
Must be compiled with the <code>-fcoarray=single</code> flag to enable use of atomic operations.
<syntaxhighlight lang="fortran">program signal_handling
use, intrinsic :: iso_fortran_env, only: atomic_logical_kind
implicit none
 
interface
let rec loop n = Console.WriteLine( n:int )
integer(C_INT) function usleep(microseconds) bind(c)
Threading.Thread.Sleep( 500 )
use, intrinsic :: iso_c_binding, only: C_INT, C_INT32_T
loop (n + 1)
integer(C_INT32_T), value :: microseconds
end function usleep
end interface
 
integer, parameter :: half_second = 500000
let main() =
integer, parameter :: sigint = 2
let start = DateTime.Now
integer, parameter :: sigquit = 3
Console.CancelKeyPress.Add(
fun _ -> let span = DateTime.Now - start
printfn "Program has run for %.0f seconds" span.TotalSeconds
)
loop 1
 
logical(atomic_logical_kind) :: interrupt_received[*]
main()</lang>
integer :: half_seconds
logical :: interrupt_received_ref
 
interrupt_received = .false.
half_seconds = 0
 
! "Install" the same signal handler for both SIGINT and SIGQUIT.
call signal(sigint, signal_handler)
call signal(sigquit, signal_handler)
 
! Indefinite loop (until one of the two signals are received).
do
if (usleep(half_second) == -1) &
print *, "Call to usleep interrupted."
 
call atomic_ref(interrupt_received_ref, interrupt_received)
if (interrupt_received_ref) then
print "(A,I0,A)", "Program ran for ", half_seconds / 2, " second(s)."
stop
end if
 
half_seconds = half_seconds + 1
print "(I0)", half_seconds
end do
 
contains
 
subroutine signal_handler(sig_num)
use, intrinsic :: iso_c_binding, only: C_INT
integer(C_INT), value, intent(in) :: sig_num
! Must be declared with attribute `value` to force pass-by-value semantics
! (what C uses by default).
 
select case (sig_num)
case (sigint)
print *, "Received SIGINT."
case (sigquit)
print *, "Received SIGQUIT."
end select
 
call atomic_define(interrupt_received, .true.)
end subroutine signal_handler
 
end program signal_handling</syntaxhighlight>
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">Dim Shared As Double start
start = Timer
 
Dim As Integer n = 1
Dim As String s
Do
Print n
s = Inkey
If s = Chr(255) + "k" Then
Dim As Double elapsed = Timer- start + n * 0.5
Print Using "Program has run for & seconds."; elapsed
End
Else
Sleep 500, 1
n += 1
End If
Loop
</syntaxhighlight>
 
 
=={{header|Gambas}}==
<syntaxhighlight lang="gambas">hTimer As Timer
fTime As Float
 
Public Sub Application_Signal(x As Integer)
 
Print "Program stopped after " & fTime & " seconds"
Quit
 
End
Public Sub Main()
hTimer = New Timer As "IntTimer"
 
Print "Press [Ctrl] + " & Chr(92) & " to stop"
 
Signal[Signal.SIGQUIT].Catch
With hTimer
.Delay = 500
.Start
End With
 
End
Public Sub IntTimer_Timer()
 
Print Rand(0, 100)
fTime += 0.5
 
End</syntaxhighlight>
Output:
<pre>
Press [Ctrl] + \ to stop
29
86
67
56
46
90
0
27
94
87
40
^\Program stopped after 5.5 seconds
</pre>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 419 ⟶ 760:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 431 ⟶ 772:
=={{header|Haskell}}==
 
<langsyntaxhighlight lang="haskell">import Prelude hiding (catch)
import Control.Exception (catch, throwIO, AsyncException(UserInterrupt))
import Data.Time.Clock (getCurrentTime, diffUTCTime)
Line 445 ⟶ 786:
loop i = do print i
threadDelay 500000 {- µs -}
loop (i + 1)</langsyntaxhighlight>
 
=={{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:
<langsyntaxhighlight HicEstlang="hicest">seconds = TIME()
 
DO i = 1, 1E100 ! "forever"
Line 460 ⟶ 801:
WRITE(Messagebox, Name) seconds
ALARM(999) ! quit immediately
END</langsyntaxhighlight>
 
==Icon and {{header|Unicon}}==
Line 466 ⟶ 807:
The following works in Unicon. I don't know if it works in Icon.
 
<langsyntaxhighlight lang="unicon">global startTime
 
procedure main()
Line 476 ⟶ 817:
procedure handler(s)
stop("\n",&now-startTime," seconds")
end</langsyntaxhighlight>
 
Sample run:
Line 494 ⟶ 835:
Use of sun.misc.SignalHandler allows one to specify which signal to catch, though is unsupported and potentially not available in all JVMs
 
<langsyntaxhighlight lang="java">import sun.misc.Signal;
import sun.misc.SignalHandler;
 
Line 513 ⟶ 854:
}
}
</syntaxhighlight>
</lang>
 
Or one can use a generic shutdown hook as follows, though a reference to the particular signal is not available.
 
<langsyntaxhighlight lang="java">public class ExampleSignalHandler {
public static void main(String... args) throws InterruptedException {
final long start = System.nanoTime();
Line 532 ⟶ 873:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 550 ⟶ 891:
=={{header|JavaScript}}==
Based on NodeJS interpreter/engine
<langsyntaxhighlight lang="javascript">(function(){
var count=0
secs=0
Line 566 ⟶ 907:
});
})();
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 581 ⟶ 922:
4.5 seconds elapsed
</pre>
 
=={{header|Jsish}}==
<syntaxhighlight lang="javascript">/* Handle a signal, is jsish */
 
var gotime = strptime();
var looping = true;
var loops = 1;
 
function handler() {
printf("Elapsed time: %ds\n", (strptime() - gotime) / 1000);
looping = false;
}
 
Signal.callback(handler, 'SIGINT');
Signal.handle('SIGINT');
 
while (looping) {
puts(loops++);
Event.update(500);
}</syntaxhighlight>
 
''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.
 
{{out}}
<pre>prompt$ jsish
Jsish interactive: see 'help [cmd]'
# source('handle-signal.jsi');
1
2
3
4
5
^CElapsed time: 2s
# </pre>
 
=={{header|Julia}}==
<syntaxhighlight lang="julia">
ccall(:jl_exit_on_sigint, Cvoid, (Cint,), 0)
 
function timeit()
<lang Julia>
ticks = 0
ccall(:jl_exit_on_sigint, Void, (Cint,), 0)
try
tic()
while true
ticks = 0
sleep(0.5)
try
ticks += 1
while true
sleep println(0.5ticks)
ticks += 1end
catch
println(ticks)
end
end
println()
toc()
</lang>
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.
 
@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}}
<pre>
Line 611 ⟶ 988:
8
9
10
11
6.020844 seconds (32.06 k allocations: 1.658 MiB)
Done.
</pre>
 
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">// version 1.1.3
 
import sun.misc.Signal
import sun.misc.SignalHandler
 
fun main(args: Array<String>) {
val startTime = System.currentTimeMillis()
 
Signal.handle(Signal("INT"), object : SignalHandler {
override fun handle(sig: Signal) {
val elapsedTime = (System.currentTimeMillis() - startTime) / 1000.0
println("\nThe program has run for $elapsedTime seconds")
System.exit(0)
}
})
 
var i = 0
while(true) {
println(i++)
Thread.sleep(500)
}
}</syntaxhighlight>
 
Sample output:
<pre>
0
1
2
3
4
5
6
7
8
9
10
^C
elapsedThe time:program 4has run for 5.689995572087 seconds
</pre>
 
=={{Headerheader|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">
<lang lb>
nomainwin
WindowHeight=DisplayHeight
Line 647 ⟶ 1,067:
if sigCtrl=1 and Inkey$=chr$(3) then sigInt=1
wait
</langsyntaxhighlight>
=={{header|Lua}}==
<syntaxhighlight lang="lua">
local start_date = os.time()
 
local loop = true
local Exit = function ()
print()
loop = false
end
 
local posix = require"posix"
posix.signal(posix.SIGINT, Exit)
posix.signal(posix.SIGQUIT, Exit)
 
local int = 0
while loop do
int = int+1
print(int)
posix.time.nanosleep{tv_sec=0,tv_nsec=500*1000*1000}
end
 
print(os.time() - start_date)
</syntaxhighlight>
{{out}}
=={{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}}
<langsyntaxhighlight MATLABlang="matlab">function sigintHandle
k = 1;
tic
Line 661 ⟶ 1,104:
k = k+1;
end
end</langsyntaxhighlight>
{{out}}
<pre>>> sigintCleanup
Line 674 ⟶ 1,117:
{{works with|MATLAB|6.1 (R12.1) and earlier}}
{{untested|MATLAB}}
<langsyntaxhighlight MATLABlang="matlab">function sigintHandle
k = 1;
tic
Line 687 ⟶ 1,130:
rethrow me
end
end</langsyntaxhighlight>
 
=={{header|NewLISP}}==
<langsyntaxhighlight NewLISPlang="newlisp">; Mac OSX, BSDs or Linux only, not Windows
(setq start-time (now))
 
Line 701 ⟶ 1,144:
 
(while (println (++ i))
(sleep 500))</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import times, os, strutils
 
let t = epochTime()
Line 714 ⟶ 1,157:
setControlCHook(handler)
 
for n in 1 .. < int64.high:
sleep 500
echo n</langsyntaxhighlight>
Or if you prefer an exception to be thrown on SIGINT:
<langsyntaxhighlight lang="nim">import times, os, strutils
 
type EKeyboardInterrupt = object of ExceptionCatchableError
 
proc handler() {.noconv.} =
Line 730 ⟶ 1,173:
 
try:
for n in 1 .. < int64.high:
sleep 500
echo n
except EKeyboardInterrupt:
echo "Program has run for ", formatFloat(epochTime() - t, precision = 0), " seconds."</langsyntaxhighlight>
 
=={{header|OCaml}}==
OCaml's <tt>Unix.sleep</tt> doesn't handle non-integral arguments, so this program prints a number every second.
 
<langsyntaxhighlight lang="ocaml">#load "unix.cma";; (* for sleep and gettimeofday; not needed for the signals stuff per se *)
 
let start = Unix.gettimeofday ();;
Line 754 ⟶ 1,197:
loop (n + 1)
in
loop 1;;</langsyntaxhighlight>
 
=={{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.
 
<syntaxhighlight lang ="perl">my $start = time;
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
{print 'Ran" 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
 
print ( ++$i," \n");
}</syntaxhighlight>
^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))
{print ++$n, "\n";}</lang>
 
This example does the required task:
<langsyntaxhighlight lang="perl">use 5.010;
use AnyEvent;
my $start = AE::time;
Line 777 ⟶ 1,265:
my $num = AE::timer 0, 0.5, sub { say $n++ };
$exit->recv;
say " interrupted after ", AE::time - $start, " seconds";</langsyntaxhighlight>
 
{{out}}
Line 795 ⟶ 1,283:
</pre>
 
=={{header|Perl 6Phix}}==
See builtins\pbreak.e for the low-level (inline assembly) cross platform signal handler,
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>
and implementation of the standard hll allow_break() and check_break() routines
<lang perl6>signal(Signal::SIGINT).tap: {
<!--<syntaxhighlight lang="phix">(notonline)-->
note "Took { now - INIT now } seconds.";
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span>
exit;
<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>
}
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Press Ctrl C\n"</span><span style="color: #0000FF;">)</span>
 
<span style="color: #004080;">atom</span> <span style="color: #000000;">t</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">time</span><span style="color: #0000FF;">()</span>
for 0, 1, *+* ... * {
<span style="color: #004080;">integer</span> <span style="color: #000000;">i</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
sleep 0.5;
<span style="color: #008080;">while</span> <span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
.say;
<span style="color: #7060A8;">sleep</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0.5</span><span style="color: #0000FF;">)</span>
}</lang>
<span style="color: #0000FF;">?</span><span style="color: #000000;">i</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">check_break</span><span style="color: #0000FF;">()</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">i</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<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>
<!--</syntaxhighlight>-->
{{out}}
<pre>0
Press Ctrl C
1
1
2
3
The program has run for 1.53 seconds
5
</pre>
8
13
21
34
55
89
^CTook 6.3437449 seconds.
Aborted</pre>
 
=={{header|PHP}}==
{{trans|Perl}}
<langsyntaxhighlight lang="php"><?php
declare(ticks = 1);
 
$start = microtime(YEStrue);
 
function mySigHandler() {
global $start;
$elapsed = microtime(YEStrue) - $start;
echo "Ran for $elapsed seconds.\n";
exit();
Line 840 ⟶ 1,327:
for ($n = 0; ; usleep(500000)) // 0.5 seconds
echo ++$n, "\n";
?></langsyntaxhighlight>
 
=={{header|PicoLisp}}==
Put the following into a file, set it to executable, and run it
<langsyntaxhighlight PicoLisplang="picolisp">#!/usr/bin/picolisp /usr/lib/picolisp/lib.l
 
(push '*Bye '(println (*/ (usec) 1000000)) '(prinl))
Line 851 ⟶ 1,338:
(loop
(println (inc 'Cnt))
(wait 500) ) )</langsyntaxhighlight>
 
=={{header|PL/I}}==
<syntaxhighlight lang="text">
handler: procedure options (main);
declare i fixed binary (31);
Line 870 ⟶ 1,357:
end;
end handler;
</syntaxhighlight>
</lang>
 
=={{header|PowerShell}}==
<langsyntaxhighlight lang="powershell">
$Start_Time = (Get-date).second
Write-Host "Type CTRL-C to Terminate..."
Line 892 ⟶ 1,379:
Write-Host "Total time in seconds"$Time_Diff
}
</syntaxhighlight>
</lang>
 
{{Out}}
Line 908 ⟶ 1,395:
=={{header|PureBasic}}==
This code is for Windows only due to the usage of SetConsoleCtrlHandler()
<langsyntaxhighlight PureBasiclang="purebasic">CompilerIf #PB_Compiler_OS<>#PB_OS_Windows
CompilerError "This code is Windows only"
CompilerEndIf
Line 929 ⟶ 1,416:
PrintN("Program has run for "+StrF((T1-T0)/1000,3)+" seconds.")
Print ("Press ENTER to exit."):Input(): i=0
EndIf</langsyntaxhighlight>
<pre>0
1
Line 940 ⟶ 1,427:
=={{header|Python}}==
Simple version
<langsyntaxhighlight lang="python">import time
 
def counter():
Line 954 ⟶ 1,441:
break
 
counter()</langsyntaxhighlight>
The following example should work on all platforms.
<langsyntaxhighlight lang="python">import time
 
def intrptWIN():
Line 973 ⟶ 1,460:
intrptWIN()
tdelt = time.time() - t1
print 'Program has run for %5.3f seconds.' % tdelt</langsyntaxhighlight>
 
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.
<langsyntaxhighlight lang="python">import signal, time, threading
done = False
n = 0
Line 1,006 ⟶ 1,493:
intrptUNIX()
tdelt = time.time() - t1
print 'Program has run for %5.3f seconds.' % tdelt</langsyntaxhighlight>
 
How about this one? It should work on all platforms;
and it does show how to install a signal handler:
<langsyntaxhighlight lang="python">import time, signal
 
class WeAreDoneException(Exception):
Line 1,032 ⟶ 1,519:
 
tdelt = time.time() - t1
print 'Program has run for %5.3f seconds.' % tdelt</langsyntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
(define now current-milliseconds)
Line 1,046 ⟶ 1,533:
(displayln i)
(sleep 0.5)))
</syntaxhighlight>
</lang>
{{out}}
<langsyntaxhighlight lang="racket">
0
1
Line 1,058 ⟶ 1,545:
7
Total time: 3.965
</syntaxhighlight>
</lang>
 
=={{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" line>signal(SIGINT).tap: {
note "Took { now - INIT now } seconds.";
exit;
}
 
for 0, 1, *+* ... * {
sleep 0.5;
.say;
}</syntaxhighlight>
{{out}}
<pre>0
1
1
2
3
5
8
13
21
34
55
89
^CTook 6.3437449 seconds.
Aborted</pre>
 
=={{header|REXX}}==
REXX has no SLEEP&nbsp; '''sleep''' &nbsp; function that is built into the language.
<br>Some operating systems that REXX runs under have a '''SLEEP''' or equivalent function.
<br><br>But, there's more than one way to skin a cat. (No offense to cat lovers.)
<lang rexx>/*REXX program displays integers until a Ctrl─C is pressed, then show*/
/* the number of seconds that have elapsed since start of pgm execution.*/
 
Some operating systems that REXX runs under have a &nbsp; '''SLEEP''' &nbsp; or equivalent BIF.
call time 'E' /*reset the REXX elapsed timer. */
signal on halt /*HALT is signaled via a Ctrl─C.*/
 
<br>But, there's more than one way to skin a cat. &nbsp; (No offense to cat lovers.)
do j=1 /*start with 1 and go ye forth. */
<syntaxhighlight lang="rexx">/*REXX program displays integers until a Ctrl─C is pressed, then shows the number of */
say right(j,20) /*display integer right-justified*/
/*────────────────────────────────── seconds that have elapsed since start of execution.*/
t=time('E') /*get the elapsed time in seconds*/
call time 'Reset' do forever; u=time('E') /*getreset the REXX elapsed timetimer. in seconds. */
signal on halt if u<t |, /*HALT: signaled via a ◄═══ meansCtrl─C we passedin midnightDOS.*/
u>t+.5 then iterate j /* ◄═══ means we passed ½ second.*/
end /*forever*/
end /*j*/
 
do j=1 /*start with unity and go ye forth. */
say 'Program control should never ever get here, said Captain Dunsel.'
say right(j,20) /*display the integer right-justified. */
t=time('E') /*get the REXX elapsed time in seconds.*/
do forever; u=time('Elapsed') /* " " " " " " " */
if u<t | u>t+.5 then iterate j /* ◄═══ passed midnight or ½ second. */
end /*forever*/
end /*j*/
 
halt: say 'program HALTed, it ran for' format(time("ELapsed"),,2) 'seconds.'
/*──────────────────────────────────HALT subroutine─────────────────────*/
/*stick a fork in it, we're all done. */</syntaxhighlight>
halt: say 'program HALTed, it ran for' format(time("E"),,2) 'seconds.'
'''output'''
/*stick a fork in it, we're done.*/</lang>
{{out}}
<pre>
1
Line 1,108 ⟶ 1,620:
21
22
^C ◄■■■■■■■■■■■■■ this where (and when) the user pressed the Crtl-C buttons.
^C
program HALTed, it ran for 11.53 seconds.
</pre>
Note: some REXX interpreters don't show the
<b>
<pre>
^C
</pre>
</b>
when &nbsp; <big> Ctrl-C </big> &nbsp; is pressed.
<br><br>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">t1 = Time.now
 
catch :done do
Line 1,133 ⟶ 1,649:
 
tdelt = Time.now - t1
puts 'Program has run for %5.3f seconds.' % tdelt</langsyntaxhighlight>
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">
#[cfg(unix)]
fn main() {
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;
use std::time::{Duration, Instant};
 
use libc::{sighandler_t, SIGINT};
 
// The time between ticks of our counter.
let duration = Duration::from_secs(1) / 2;
 
// "SIGINT received" global variable.
static mut GOT_SIGINT: AtomicBool = AtomicBool::new(false);
 
unsafe {
// Initially, "SIGINT received" is false.
GOT_SIGINT.store(false, Ordering::Release);
// Interrupt handler that handles the SIGINT signal
unsafe fn handle_sigint() {
// It is dangerous to perform any system calls in interrupts, so just set the atomic
// "SIGINT received" global to true when it arrives.
GOT_SIGINT.store(true, Ordering::Release);
}
// Make handle_sigint the signal handler for SIGINT.
libc::signal(SIGINT, handle_sigint as sighandler_t);
}
 
// Get the start time...
let start = Instant::now();
 
// Integer counter
let mut i = 0u32;
 
// Every `duration`...
loop {
thread::sleep(duration);
 
// Break if SIGINT was handled
if unsafe { GOT_SIGINT.load(Ordering::Acquire) } {
break;
}
 
// Otherwise, increment and display the integer and continue the loop.
i += 1;
println!("{}", i);
}
 
// Get the elapsed time.
let elapsed = start.elapsed();
 
// Print the difference and exit
println!("Program has run for {} seconds", elapsed.as_secs());
}
 
#[cfg(not(unix))]
fn main() {
println!("Not supported on this platform");
}
 
</syntaxhighlight>
 
 
=={{header|Scala}}==
{{libheader|Scala}}
<langsyntaxhighlight Scalalang="scala">import sun.misc.Signal
import sun.misc.SignalHandler
 
Line 1,156 ⟶ 1,736:
Thread.sleep(500)
}
}</langsyntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">var start = Time.sec;
 
Sig.INT {
Sys.say( "Ran for #{Time.sec - start} seconds.");
Sys.exit;
};
 
{ |i|
Sys.say( i);
Sys.sleep(0.5);
} * Math.inf;Inf</langsyntaxhighlight>
{{out}}
<pre>
1
2
3
4
^CRan for 2 seconds.
</pre>
 
=={{header|Smalltalk}}==
{{works with|Smalltalk/X}}<langsyntaxhighlight lang="smalltalk">|n|
 
n := 0.
Line 1,182 ⟶ 1,770:
Delay waitForSeconds: 0.5.
]
]</langsyntaxhighlight>
or:
<langsyntaxhighlight lang="smalltalk">[ ... do something... ] on: UserInterrupt do: [:exInfo | ...handler... ]</langsyntaxhighlight>
 
attaching an OS-signal (unix signal) to an exception or signal instance:
<langsyntaxhighlight lang="smalltalk">|mySignal|
mySignal := Signal new mayProceed: false.
OperatingSytem operatingSystemSignal: (OperatingSystem signalNamed:'SIGHUP') install: mySignal.
Line 1,194 ⟶ 1,782:
] on: mySignal do:[
... handle SIGHUP gracefully...
]</langsyntaxhighlight>
As the runtime system already catches common unix signals
and arranges for an OSError to be raised,
user code normally does not need to care for this
(except for those who want to change that very runtime system behavior ;-).
 
=={{header|Swift}}==
{{trans|C}}
<syntaxhighlight lang="swift">import Foundation
 
let startTime = NSDate()
var signalReceived: sig_atomic_t = 0
 
signal(SIGINT) { signal in signalReceived = 1 }
 
for var i = 0;; {
if signalReceived == 1 { break }
usleep(500_000)
if signalReceived == 1 { break }
print(++i)
}
 
let endTime = NSDate()
print("Program has run for \(endTime.timeIntervalSinceDate(startTime)) seconds")
 
</syntaxhighlight>
 
=={{header|Tcl}}==
Line 1,205 ⟶ 1,814:
 
Using Expect:
<langsyntaxhighlight lang="tcl">package require Expect
 
proc sigint_handler {} {
Line 1,220 ⟶ 1,829:
puts [incr n]
after 500
}</langsyntaxhighlight>
 
Similarly, with TclX:
<langsyntaxhighlight lang="tcl">package require Tclx
 
proc sigint_handler {} {
Line 1,238 ⟶ 1,847:
puts [incr n]
after 500
}</langsyntaxhighlight>
 
With TclX, you don't have to trap signals,
you can convert the signal into a catchable error:
<langsyntaxhighlight lang="tcl">package require Tclx
 
signal error sigint
Line 1,261 ⟶ 1,870:
puts "infinite loop interrupted, but not on SIGINT: $::errorInfo"
}
}</langsyntaxhighlight>
 
With Tcl 8.6, that would be written as:
<langsyntaxhighlight lang="tcl">package require Tclx
 
signal error sigint
Line 1,279 ⟶ 1,888:
} trap {POSIX SIG SIGINT} {} {
puts "elapsed time: [expr {[clock seconds] - $start_time}] seconds"
}</langsyntaxhighlight>
 
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.
 
=={{header|X86 Assembly}}==
{{works with|NASM|Linux}}<br>
Now, I realize linking to C libraries is somewhat cheating.
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.
<lang asm>
%define sys_signal 48
%define SIGINT 2
%define sys_time 13
 
extern usleep
extern printf
 
section .text
global _start
_sig_handler:
mov ebx, end_time
mov eax, sys_time
int 0x80
mov eax, dword [start_time]
mov ebx, dword [end_time]
sub ebx, eax
mov ax, 100
div ebx
push ebx
push p_time
call printf
push 0x1
mov eax, 1
push eax
int 0x80
ret
_start:
mov ebx, start_time
mov eax, sys_time
int 0x80
mov ecx, _sig_handler
mov ebx, SIGINT
mov eax, sys_signal
int 0x80
xor edi, edi
.looper:
push 500000
call usleep
push edi
push p_cnt
call printf
inc edi
jmp .looper
section .data
p_time db "The program has run for %d seconds.",13,10,0
p_cnt db "%d",13,10,0
 
section .bss
start_time resd 1
end_time resd 1
</lang>
 
 
=={{header|TXR}}==
 
<syntaxhighlight lang="txr">(set-sig-handler sig-int
<lang txr>@(do
(lambda (signum async-p)
(set-sig-handler sig-int
(lambdathrowf (signum'error async-p"caught signal ~s" signum)))
(throwf 'error "caught signal ~s" signum)))
 
(let ((start-time (time)))
(catch (each ((num (range 1)))
(format t "~s\n" num)
(usleep 500000))
(error (msg)
(let ((end-time (time)))
(format t "\n\n~a after ~s seconds of execution\n"
msg (- end-time start-time)))))))</langsyntaxhighlight>
 
{{out|Run}}
<pre>$ txr handle-a-signal.txrtl
1
2
Line 1,389 ⟶ 1,935:
that signals the shell every half a second.
 
<langsyntaxhighlight lang="bash">c="1"
# 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,395 ⟶ 1,941:
# wait 0.5 # We need a helper program for the half second interval
c=`expr $c + 1`
done</langsyntaxhighlight>
 
{{works with|bash}}
Note that the following solution only works on systems
that support a version of sleep that can handle non-integers.
<langsyntaxhighlight lang="bash">
#!/bin/bash
trap 'echo "Run for $((s/2)) seconds"; exit' 2
Line 1,411 ⟶ 1,957:
let s++
done
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,429 ⟶ 1,975:
with a 5 tenths of a second timeout:
 
<langsyntaxhighlight lang="bash">#!/bin/bash
trap 'echo "Run for $((s/2)) seconds"; exit' 2
s=1
Line 1,447 ⟶ 1,993:
half_sec_sleep
let s++
done</langsyntaxhighlight>
 
{{works with|zsh}}
<langsyntaxhighlight lang="bash">TRAPINT(){ print $n; exit }
for (( n = 0; ; n++)) sleep 1</langsyntaxhighlight>
 
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<syntaxhighlight lang="vbnet">Module Module1
Dim startTime As Date
 
Sub Main()
startTime = Date.Now
' Add event handler for Cntrl+C command
AddHandler Console.CancelKeyPress, AddressOf Console_CancelKeyPress
 
Dim counter = 0
While True
counter += 1
Console.WriteLine(counter)
Threading.Thread.Sleep(500)
End While
End Sub
 
Sub Console_CancelKeyPress(sender As Object, e As ConsoleCancelEventArgs)
Dim stopTime = Date.Now
Console.WriteLine("This program ran for {0:000.000} seconds", (stopTime - startTime).TotalMilliseconds / 1000)
Environment.Exit(0)
End Sub
 
End Module</syntaxhighlight>
 
=={{header|Visual FoxPro}}==
<langsyntaxhighlight lang="vfp">
*!* In VFP, Ctrl+C is normally used to copy text to the clipboard.
*!* Esc is used to stop execution.
Line 1,478 ⟶ 2,050:
lLoop = .F.
ENDPROC
</syntaxhighlight>
</lang>
 
=={{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.
<syntaxhighlight lang="wren">import "scheduler" for Scheduler
import "timer" for Timer
import "io" for Stdin
 
var start = System.clock
var stop = false
 
Scheduler.add {
var n = 0
while (true) {
System.print(n)
if (stop) {
var elapsed = System.clock - start + n * 0.5
System.print("Program has run for %(elapsed) seconds.")
return
}
Timer.sleep(500)
n = n + 1
}
}
 
Stdin.isRaw = true // enable control characters to go into stdin
while (true) {
var b = Stdin.readByte()
if (b == 3 || b == 28) break // quits on pressing either Ctrl-C os Ctrl-\
}
Stdin.isRaw = false
stop = true</syntaxhighlight>
 
{{out}}
Sample run:
<pre>
0
1
2
3
4
5
6
7
8
9
10
11
12
Program has run for 6.00173 seconds.
</pre>
 
=={{header|X86 Assembly}}==
{{works with|NASM|Linux}}<br>
Now, I realize linking to C libraries is somewhat cheating.
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.
<syntaxhighlight lang="asm">
%define sys_signal 48
%define SIGINT 2
%define sys_time 13
 
extern usleep
extern printf
 
section .text
global _start
_sig_handler:
mov ebx, end_time
mov eax, sys_time
int 0x80
mov eax, dword [start_time]
mov ebx, dword [end_time]
sub ebx, eax
mov ax, 100
div ebx
push ebx
push p_time
call printf
push 0x1
mov eax, 1
push eax
int 0x80
ret
_start:
mov ebx, start_time
mov eax, sys_time
int 0x80
mov ecx, _sig_handler
mov ebx, SIGINT
mov eax, sys_signal
int 0x80
xor edi, edi
.looper:
push 500000
call usleep
push edi
push p_cnt
call printf
inc edi
jmp .looper
section .data
p_time db "The program has run for %d seconds.",13,10,0
p_cnt db "%d",13,10,0
 
section .bss
start_time resd 1
end_time resd 1
</syntaxhighlight>
 
=={{header|zkl}}==
SigInt is the only signal zkl brings out.
<langsyntaxhighlight lang="zkl">var t=Time.Clock.time;
try{ n:=0; while(1){(n+=1).println(); Atomic.sleep(0.5)} }
catch{ println("ran for ",Time.Clock.time-t," seconds"); System.exit() }</langsyntaxhighlight>
{{out}}
<pre>
Anonymous user