Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,7 @@
---
category:
- Signal handling
from: http://rosettacode.org/wiki/Handle_a_signal
note: Concurrency
requires:
- Signal handling

View file

@ -0,0 +1,10 @@
Most 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:
Provide a program that displays an integer on each line of output at the rate of about one per 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 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-->
<br><br>

View file

@ -0,0 +1,14 @@
with Ada.Interrupts; use Ada.Interrupts;
with Ada.Interrupts.Names; use Ada.Interrupts.Names;
package Sigint_Handler is
protected Handler is
entry Wait;
procedure Handle;
pragma Interrupt_Handler(Handle);
pragma Attach_Handler(Handle, Sigint);
private
Call_Count : Natural := 0;
end Handler;
end Sigint_Handler;

View file

@ -0,0 +1,29 @@
package body Sigint_Handler is
-------------
-- Handler --
-------------
protected body Handler is
----------
-- Wait --
----------
entry Wait when Call_Count > 0 is
begin
Call_Count := Call_Count - 1;
end Wait;
------------
-- Handle --
------------
procedure Handle is
begin
Call_Count := Call_Count + 1;
end Handle;
end Handler;
end Sigint_Handler;

View file

@ -0,0 +1,37 @@
with Ada.Calendar; use Ada.Calendar;
with Ada.Text_Io; use Ada.Text_Io;
with Sigint_Handler; use Sigint_Handler;
procedure Signals is
task Counter is
entry Stop;
end Counter;
task body Counter is
Current_Count : Natural := 0;
begin
loop
select
accept Stop;
exit;
or delay 0.5;
end select;
Current_Count := Current_Count + 1;
Put_Line(Natural'Image(Current_Count));
end loop;
end Counter;
task Sig_Handler;
task body Sig_Handler is
Start_Time : Time := Clock;
Sig_Time : Time;
begin
Handler.Wait;
Sig_Time := Clock;
Counter.Stop;
Put_Line("Program execution took" & Duration'Image(Sig_Time - Start_Time) & " seconds");
end Sig_Handler;
begin
null;
end Signals;

View file

@ -0,0 +1,15 @@
Start:=A_TickCount
counter=0
SetTimer, timer, 500
return
timer:
Send % ++Counter "`n"
return
^c::
SetTimer, timer, off
SetFormat, float, 0.3
Send, % "Task took " (A_TickCount-Start)/1000 " Seconds"
ExitApp
return

View file

@ -0,0 +1,33 @@
REM!Exefile C:\bbcsigint.exe,encrypt,console
INSTALL @lib$+"CALLBACK"
CTRL_C_EVENT = 0
SYS "GetStdHandle", -10 TO @hfile%(1)
SYS "GetStdHandle", -11 TO @hfile%(2)
*INPUT 13
*OUTPUT 14
ON ERROR PRINT REPORT$ : QUIT ERR
CtrlC% = FALSE
handler% = FN_callback(FNsigint(), 1)
SYS FN_syscalls("SetConsoleCtrlHandler"), handler%, 1 TO !FN_systo(res%)
IF res%=0 PRINT "Could not set SIGINT handler" : QUIT 1
PRINT "Press Ctrl+C to test...."
TIME = 0
Time% = 50
REPEAT
WAIT 1
IF TIME > Time% THEN
PRINT Time%
Time% += 50
ENDIF
UNTIL CtrlC%
PRINT "Ctrl+C was pressed after "; TIME/100 " seconds."
QUIT
DEF FNsigint(T%)
CASE T% OF
WHEN CTRL_C_EVENT: CtrlC% = TRUE : = 1
ENDCASE
= 0

View file

@ -0,0 +1,14 @@
' Handle signal
SUB Finished
SIGNAL SIG_DFL, SIGINT : ' Restore SIGINT to default
PRINT "Running for", TIMER / 1000.0, "seconds" FORMAT "%s %f %s\n"
STOP SIGINT : ' Send another terminating SIGINT
ENDSUB
SIGNAL Finished, SIGINT
iter = 1
WHILE TRUE
SLEEP 500
PRINT iter
iter = iter + 1
WEND

View file

@ -0,0 +1,33 @@
#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;
}

View file

@ -0,0 +1,23 @@
using System; //DateTime, Console, Environment classes
class Program
{
static DateTime start;
static void Main(string[] args)
{
start = DateTime.Now;
//Add event handler for Ctrl+C command
Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
int counter = 0;
while (true)
{
Console.WriteLine(++counter);
System.Threading.Thread.Sleep(500);
}
}
static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
var end = DateTime.Now;
Console.WriteLine("This program ran for {0:000.000} seconds.", (end - start).TotalMilliseconds / 1000);
Environment.Exit(0);
}
}

View file

@ -0,0 +1,33 @@
#include <stdio.h>
#include <stdlib.h> // for exit()
#include <signal.h>
#include <time.h> // for clock()
#include <unistd.h> // for POSIX usleep()
volatile sig_atomic_t gotint = 0;
void handleSigint() {
/*
* Signal safety: It is not safe to call clock(), printf(),
* or exit() inside a signal handler. Instead, we set a flag.
*/
gotint = 1;
}
int main() {
clock_t startTime = clock();
signal(SIGINT, handleSigint);
int i=0;
for (;;) {
if (gotint)
break;
usleep(500000);
if (gotint)
break;
printf("%d\n", ++i);
}
clock_t endTime = clock();
double td = (endTime - startTime) / (double)CLOCKS_PER_SEC;
printf("Program has run for %5.3f seconds\n", td);
return 0;
}

View file

@ -0,0 +1,44 @@
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.

View file

@ -0,0 +1,15 @@
(require 'clojure.repl)
(def start (System/nanoTime))
(defn shutdown [_]
(println "Received INT after"
(/ (- (System/nanoTime) start) 1e9)
"seconds.")
(System/exit 0))
(clojure.repl/set-break-handler! shutdown)
(doseq [i (range)]
(prn i)
(Thread/sleep 500))

View file

@ -0,0 +1,22 @@
(ql:quickload :cffi)
(defconstant +SIGINT+ 2)
(defmacro set-signal-handler (signo &body body)
(let ((handler (gensym "HANDLER")))
`(progn
(cffi:defcallback ,handler :void ((signo :int))
(declare (ignore signo))
,@body)
(cffi:foreign-funcall "signal" :int ,signo :pointer (cffi:callback ,handler)))))
(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))
(let ((i 0))
(loop do
(format t "~a~&" (incf i))
(sleep 0.5)))

View file

@ -0,0 +1,24 @@
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

View file

@ -0,0 +1,29 @@
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);
}

View file

@ -0,0 +1,22 @@
#! /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).

View file

@ -0,0 +1,15 @@
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()

View file

@ -0,0 +1,15 @@
-28 constant SIGINT
: numbers ( n -- n' )
begin dup . cr 1+ 500 ms again ;
: main
utime
0 begin
['] numbers catch
SIGINT =
until drop
utime d- dnegate
<# # # # # # # [char] . hold #s #> type ." seconds" ;
main bye

View file

@ -0,0 +1,60 @@
program signal_handling
use, intrinsic :: iso_fortran_env, only: atomic_logical_kind
implicit none
interface
integer(C_INT) function usleep(microseconds) bind(c)
use, intrinsic :: iso_c_binding, only: C_INT, C_INT32_T
integer(C_INT32_T), value :: microseconds
end function usleep
end interface
integer, parameter :: half_second = 500000
integer, parameter :: sigint = 2
integer, parameter :: sigquit = 3
logical(atomic_logical_kind) :: interrupt_received[*]
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

View file

@ -0,0 +1,17 @@
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

View file

@ -0,0 +1,31 @@
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

View file

@ -0,0 +1,28 @@
package main
import (
"fmt"
"os"
"os/signal"
"time"
)
func main() {
start := time.Now()
k := time.Tick(time.Second / 2)
sc := make(chan os.Signal, 1)
signal.Notify(sc, os.Interrupt)
for n := 1; ; {
// not busy waiting, this blocks until one of the two
// channel operations is possible
select {
case <-k:
fmt.Println(n)
n++
case <-sc:
fmt.Printf("Ran for %f seconds.\n",
time.Now().Sub(start).Seconds())
return
}
}
}

View file

@ -0,0 +1,15 @@
import Prelude hiding (catch)
import Control.Exception (catch, throwIO, AsyncException(UserInterrupt))
import Data.Time.Clock (getCurrentTime, diffUTCTime)
import Control.Concurrent (threadDelay)
main = do t0 <- getCurrentTime
catch (loop 0)
(\e -> if e == UserInterrupt
then do t1 <- getCurrentTime
putStrLn ("\nTime: " ++ show (diffUTCTime t1 t0))
else throwIO e)
loop i = do print i
threadDelay 500000 {- µs -}
loop (i + 1)

View file

@ -0,0 +1,12 @@
seconds = TIME()
DO i = 1, 1E100 ! "forever"
SYSTEM(WAIT = 500) ! milli seconds
WRITE(Name) i
ENDDO
SUBROUTINE F2 ! call by either the F2 key, or by a toolbar-F2 click
seconds = TIME() - seconds
WRITE(Messagebox, Name) seconds
ALARM(999) ! quit immediately
END

View file

@ -0,0 +1,11 @@
global startTime
procedure main()
startTime := &now
trap("SIGINT", handler)
every write(seq()) do delay(500)
end
procedure handler(s)
stop("\n",&now-startTime," seconds")
end

View file

@ -0,0 +1,19 @@
import sun.misc.Signal;
import sun.misc.SignalHandler;
public class ExampleSignalHandler {
public static void main(String... args) throws InterruptedException {
final long start = System.nanoTime();
Signal.handle(new Signal("INT"), new SignalHandler() {
public void handle(Signal sig) {
System.out.format("\nProgram execution took %f seconds\n", (System.nanoTime() - start) / 1e9f);
System.exit(0);
}
});
int counter = 0;
while(true) {
System.out.println(counter++);
Thread.sleep(500);
}
}
}

View file

@ -0,0 +1,15 @@
public class ExampleSignalHandler {
public static void main(String... args) throws InterruptedException {
final long start = System.nanoTime();
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
public void run() {
System.out.format("\nProgram execution took %f seconds\n", (System.nanoTime() - start) / 1e9f);
}
}));
int counter = 0;
while(true) {
System.out.println(counter++);
Thread.sleep(500);
}
}
}

View file

@ -0,0 +1,16 @@
(function(){
var count=0
secs=0
var i= setInterval( function (){
count++
secs+=0.5
console.log(count)
}, 500);
process.on('SIGINT', function() {
clearInterval(i)
console.log(secs+' seconds elapsed');
process.exit()
});
})();

View file

@ -0,0 +1,18 @@
/* 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);
}

View file

@ -0,0 +1,16 @@
ccall(:jl_exit_on_sigint, Cvoid, (Cint,), 0)
function timeit()
ticks = 0
try
while true
sleep(0.5)
ticks += 1
println(ticks)
end
catch
end
end
@time timeit()
println("Done.")

View file

@ -0,0 +1,22 @@
// 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)
}
}

View file

@ -0,0 +1,29 @@
nomainwin
WindowHeight=DisplayHeight
open "Handle a signal" for graphics as #1
#1 "trapclose [quit]"
#1 "down;setfocus;place 10 20"
#1 "\Press CTRL + C to stop."
#1 "when characterInput [keyPressed]"
start=time$("ms")
timer 500, [doPrint]
wait
[quit] close #1:end
[doPrint]
if sigInt then
timer 0
#1 "\Seconds elapsed: ";(time$("ms")-start)/1000
else
i=i+1
if i mod 20 = 0 then #1 "cls;place 10 20"
#1 "\";i
end if
wait
[keyPressed]
if len(Inkey$)>1 then
if left$(Inkey$,1)=chr$(8) then sigCtrl=1 else sigCtrl=0
end if
if sigCtrl=1 and Inkey$=chr$(3) then sigInt=1
wait

View file

@ -0,0 +1,10 @@
function sigintHandle
k = 1;
tic
catchObj = onCleanup(@toc);
while true
pause(0.5)
fprintf('%d\n', k)
k = k+1;
end
end

View file

@ -0,0 +1,14 @@
function sigintHandle
k = 1;
tic
try
while true
pause(0.5)
fprintf('%d\n', k)
k = k+1;
end
catch me
toc
rethrow me
end
end

View file

@ -0,0 +1,12 @@
; Mac OSX, BSDs or Linux only, not Windows
(setq start-time (now))
(signal 2 (lambda()
(println
(format "Program has run for %d seconds"
(- (apply date-value (now))
(apply date-value start-time))))
(exit 0)))
(while (println (++ i))
(sleep 500))

View file

@ -0,0 +1,13 @@
import times, os, strutils
let t = epochTime()
proc handler() {.noconv.} =
echo "Program has run for ", formatFloat(epochTime() - t, precision = 0), " seconds."
quit 0
setControlCHook(handler)
for n in 1 ..< int64.high:
sleep 500
echo n

View file

@ -0,0 +1,17 @@
import times, os, strutils
type EKeyboardInterrupt = object of CatchableError
proc handler() {.noconv.} =
raise newException(EKeyboardInterrupt, "Keyboard Interrupt")
setControlCHook(handler)
let t = epochTime()
try:
for n in 1 ..< int64.high:
sleep 500
echo n
except EKeyboardInterrupt:
echo "Program has run for ", formatFloat(epochTime() - t, precision = 0), " seconds."

View file

@ -0,0 +1,16 @@
#load "unix.cma";; (* for sleep and gettimeofday; not needed for the signals stuff per se *)
let start = Unix.gettimeofday ();;
Sys.set_signal Sys.sigint
(Sys.Signal_handle (fun _signum ->
Printf.printf "Ran for %f seconds.\n"
(Unix.gettimeofday () -. start);
exit 0));;
let rec loop n =
Printf.printf "%d\n%!" n;
Unix.sleep 1;
loop (n + 1)
in
loop 1;;

View file

@ -0,0 +1,17 @@
<?php
declare(ticks = 1);
$start = microtime(true);
function mySigHandler() {
global $start;
$elapsed = microtime(true) - $start;
echo "Ran for $elapsed seconds.\n";
exit();
}
pcntl_signal(SIGINT, 'mySigHandler');
for ($n = 0; ; usleep(500000)) // 0.5 seconds
echo ++$n, "\n";
?>

View file

@ -0,0 +1,15 @@
handler: procedure options (main);
declare i fixed binary (31);
declare (start_time, finish_time) float (18);
on attention begin;
finish_time = secs();
put skip list ('elapsed time =', finish_time - start_time, 'secs');
stop;
end;
start_time = secs();
do i = 1 by 1;
delay (500);
put skip list (i);
end;
end handler;

View file

@ -0,0 +1,21 @@
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 " Running for ", time - $start, " seconds.\n"; };
$SIG{ALRM} = sub
{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");
}

View file

@ -0,0 +1,9 @@
use 5.010;
use AnyEvent;
my $start = AE::time;
my $exit = AE::cv;
my $int = AE::signal 'INT', $exit;
my $n;
my $num = AE::timer 0, 0.5, sub { say $n++ };
$exit->recv;
say " interrupted after ", AE::time - $start, " seconds";

View file

@ -0,0 +1,14 @@
(notonline)-->
<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>
<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>
<span style="color: #004080;">integer</span> <span style="color: #000000;">i</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
<span style="color: #7060A8;">sleep</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0.5</span><span style="color: #0000FF;">)</span>
<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>
<!--

View file

@ -0,0 +1,8 @@
#!/usr/bin/picolisp /usr/lib/picolisp/lib.l
(push '*Bye '(println (*/ (usec) 1000000)) '(prinl))
(let Cnt 0
(loop
(println (inc 'Cnt))
(wait 500) ) )

View file

@ -0,0 +1,18 @@
$Start_Time = (Get-date).second
Write-Host "Type CTRL-C to Terminate..."
$n = 1
Try
{
While($true)
{
Write-Host $n
$n ++
Start-Sleep -m 500
}
}
Finally
{
$End_Time = (Get-date).second
$Time_Diff = $End_Time - $Start_Time
Write-Host "Total time in seconds"$Time_Diff
}

View file

@ -0,0 +1,22 @@
CompilerIf #PB_Compiler_OS<>#PB_OS_Windows
CompilerError "This code is Windows only"
CompilerEndIf
Global Quit, i, T0=ElapsedMilliseconds(), T1
Procedure CtrlC()
T1=ElapsedMilliseconds()
Quit=1
While i: Delay(1): Wend
EndProcedure
If OpenConsole()
SetConsoleCtrlHandler_(@CtrlC(),#True)
While Not Quit
PrintN(Str(i))
i+1
Delay(500)
Wend
PrintN("Program has run for "+StrF((T1-T0)/1000,3)+" seconds.")
Print ("Press ENTER to exit."):Input(): i=0
EndIf

View file

@ -0,0 +1,15 @@
import time
def counter():
n = 0
t1 = time.time()
while True:
try:
time.sleep(0.5)
n += 1
print n
except KeyboardInterrupt, e:
print 'Program has run for %5.3f seconds.' % (time.time() - t1)
break
counter()

View file

@ -0,0 +1,18 @@
import time
def intrptWIN():
procDone = False
n = 0
while not procDone:
try:
time.sleep(0.5)
n += 1
print n
except KeyboardInterrupt, e:
procDone = True
t1 = time.time()
intrptWIN()
tdelt = time.time() - t1
print 'Program has run for %5.3f seconds.' % tdelt

View file

@ -0,0 +1,29 @@
import signal, time, threading
done = False
n = 0
def counter():
global n, timer
n += 1
print n
timer = threading.Timer(0.5, counter)
timer.start()
def sigIntHandler(signum, frame):
global done
timer.cancel()
done = True
def intrptUNIX():
global timer
signal.signal(signal.SIGINT, sigIntHandler)
timer = threading.Timer(0.5, counter)
timer.start()
while not done:
signal.pause()
t1 = time.time()
intrptUNIX()
tdelt = time.time() - t1
print 'Program has run for %5.3f seconds.' % tdelt

View file

@ -0,0 +1,23 @@
import time, signal
class WeAreDoneException(Exception):
pass
def sigIntHandler(signum, frame):
signal.signal(signal.SIGINT, signal.SIG_DFL) # resets to default handler
raise WeAreDoneException
t1 = time.time()
try:
signal.signal(signal.SIGINT, sigIntHandler)
n = 0
while True:
time.sleep(0.5)
n += 1
print n
except WeAreDoneException:
pass
tdelt = time.time() - t1
print 'Program has run for %5.3f seconds.' % tdelt

View file

@ -0,0 +1,15 @@
/*REXX program displays integers until a Ctrl─C is pressed, then shows the number of */
/*────────────────────────────────── seconds that have elapsed since start of execution.*/
call time 'Reset' /*reset the REXX elapsed timer. */
signal on halt /*HALT: signaled via a Ctrl─C in DOS.*/
do j=1 /*start with unity and go ye forth. */
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.'
/*stick a fork in it, we're all done. */

View file

@ -0,0 +1,10 @@
#lang racket
(define now current-milliseconds)
(define start (now))
(with-handlers ([exn:break?
(λ(x)
(define elapsed (/ (- (now) start) 1000.))
(displayln (~a "Total time: " elapsed)))])
(for ([i (in-naturals)])
(displayln i)
(sleep 0.5)))

View file

@ -0,0 +1,9 @@
0
1
2
3
4
5
6
7
Total time: 3.965

View file

@ -0,0 +1,9 @@
signal(SIGINT).tap: {
note "Took { now - INIT now } seconds.";
exit;
}
for 0, 1, *+* ... * {
sleep 0.5;
.say;
}

View file

@ -0,0 +1,17 @@
t1 = Time.now
catch :done do
Signal.trap('INT') do
Signal.trap('INT', 'DEFAULT') # reset to default
throw :done
end
n = 0
loop do
sleep(0.5)
n += 1
puts n
end
end
tdelt = Time.now - t1
puts 'Program has run for %5.3f seconds.' % tdelt

View file

@ -0,0 +1,58 @@
#[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");
}

View file

@ -0,0 +1,20 @@
import sun.misc.Signal
import sun.misc.SignalHandler
object SignalHandl extends App {
val start = System.nanoTime()
var counter = 0
Signal.handle(new Signal("INT"), new SignalHandler() {
def handle(sig: Signal) {
println(f"\nProgram execution took ${(System.nanoTime() - start) / 1e9f}%f seconds\n")
exit(0)
}
})
while (true) {
counter += 1
println(counter)
Thread.sleep(500)
}
}

View file

@ -0,0 +1,11 @@
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;

View file

@ -0,0 +1,11 @@
|n|
n := 0.
UserInterrupt
catch:[
[true] whileTrue:[
n := n + 1.
n printCR.
Delay waitForSeconds: 0.5.
]
]

View file

@ -0,0 +1 @@
[ ... do something... ] on: UserInterrupt do: [:exInfo | ...handler... ]

View file

@ -0,0 +1,8 @@
|mySignal|
mySignal := Signal new mayProceed: false.
OperatingSytem operatingSystemSignal: (OperatingSystem signalNamed:'SIGHUP') install: mySignal.
[
.. do something...
] on: mySignal do:[
... handle SIGHUP gracefully...
]

View file

@ -0,0 +1,16 @@
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")

View file

@ -0,0 +1,12 @@
(set-sig-handler sig-int
(lambda (signum async-p)
(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))))))

View file

@ -0,0 +1,16 @@
package require Expect
proc sigint_handler {} {
puts "elapsed time: [expr {[clock seconds] - $::start_time}] seconds"
set ::looping false
}
trap sigint_handler SIGINT
set start_time [clock seconds]
set n 0
set looping true
while {$looping} {
puts [incr n]
after 500
}

View file

@ -0,0 +1,16 @@
package require Tclx
proc sigint_handler {} {
puts "elapsed time: [expr {[clock seconds] - $::start_time}] seconds"
set ::looping false
}
signal trap sigint sigint_handler
set start_time [clock seconds]
set n 0
set looping true
while {$looping} {
puts [incr n]
after 500
}

View file

@ -0,0 +1,20 @@
package require Tclx
signal error sigint
set start_time [clock seconds]
set n 0
proc infinite_loop {} {
while 1 {
puts [incr n]
after 500
}
}
if {[catch infinite_loop out] != 0} {
lassign $::errorCode class name msg
if {$class eq "POSIX" && $name eq "SIG" && $msg eq "SIGINT"} {
puts "elapsed time: [expr {[clock seconds] - $start_time}] seconds"
} else {
puts "infinite loop interrupted, but not on SIGINT: $::errorInfo"
}
}

View file

@ -0,0 +1,16 @@
package require Tclx
signal error sigint
set start_time [clock seconds]
proc infinite_loop {} {
while 1 {
puts [incr n]
after 500
}
}
try {
infinite_loop
} trap {POSIX SIG SIGINT} {} {
puts "elapsed time: [expr {[clock seconds] - $start_time}] seconds"
}

View file

@ -0,0 +1,7 @@
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
while [ "$c" -ne 0 ]; do # infinite loop
# wait 0.5 # We need a helper program for the half second interval
c=`expr $c + 1`
done

View file

@ -0,0 +1,10 @@
#!/bin/bash
trap 'echo "Run for $((s/2)) seconds"; exit' 2
s=1
while true
do
echo $s
sleep .5
let s++
done

View file

@ -0,0 +1,19 @@
#!/bin/bash
trap 'echo "Run for $((s/2)) seconds"; exit' 2
s=1
half_sec_sleep()
{
local save_tty=$(stty -g)
stty -icanon time 5 min 0
read
stty $save_tty
}
while true
do
echo $s
half_sec_sleep
let s++
done

View file

@ -0,0 +1,2 @@
TRAPINT(){ print $n; exit }
for (( n = 0; ; n++)) sleep 1

View file

@ -0,0 +1,23 @@
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

View file

@ -0,0 +1,23 @@
*!* In VFP, Ctrl+C is normally used to copy text to the clipboard.
*!* Esc is used to stop execution.
CLEAR
SET ESCAPE ON
ON ESCAPE DO StopLoop
CLEAR DLLS
DECLARE Sleep IN WIN32API INTEGER nMilliSeconds
lLoop = .T.
n = 0
? "Press Esc to Cancel..."
t1 = INT(SECONDS())
DO WHILE lLoop
n = n + 1
? n
Sleep(500)
ENDDO
? "Elapsed time:", TRANSFORM(INT(SECONDS()) - t1) + " secs."
CLEAR DLLS
RETURN TO MASTER
PROCEDURE StopLoop
lLoop = .F.
ENDPROC

View file

@ -0,0 +1,28 @@
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

View file

@ -0,0 +1,53 @@
%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

View file

@ -0,0 +1,3 @@
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() }