Previous: linux timerfd api, Up: linux timerfd [Index]
timerfd APIThe following program watches a timer as time goes by:
#!r6rs
(import (vicare)
(vicare platform constants)
(only (vicare language-extensions syntaxes)
unwind-protect)
(prefix (vicare posix) px.)
(prefix (vicare linux) lx.))
(set-port-buffer-mode! (current-output-port)
(buffer-mode none))
(define (%print-remaining-time fd)
(pretty-print (lx.struct-itimerspec-it_value
(lx.timerfd-gettime fd))))
(define (%sleep-one-second)
(px.nanosleep 1 0))
(let ((fd (lx.timerfd-create CLOCK_REALTIME)))
(unwind-protect
(let ( ;; one event every 3 seconds
(period (lx.make-struct-timespec 3 0))
;; the first event after 1 nanosecond
(offset (lx.make-struct-timespec 0 1)))
(lx.timerfd-settime fd 0
(lx.make-struct-itimerspec period offset))
(do ((i 0 (fx+ 1 i)))
((fx= i 6))
(%print-remaining-time fd)
(%sleep-one-second))
#f)
(px.close fd)))
the output is:
#["struct-timespec" tv_sec=2 tv_nsec=999911022] #["struct-timespec" tv_sec=1 tv_nsec=999307638] #["struct-timespec" tv_sec=0 tv_nsec=998303788] #["struct-timespec" tv_sec=2 tv_nsec=997338092] #["struct-timespec" tv_sec=1 tv_nsec=996393490] #["struct-timespec" tv_sec=0 tv_nsec=995418649]
The following example prints the number of timer expirations:
#!r6rs
(import (vicare)
(vicare platform constants)
(only (vicare language-extensions syntaxes)
unwind-protect)
(prefix (vicare posix) px.)
(prefix (vicare linux) lx.))
(set-port-buffer-mode! (current-output-port)
(buffer-mode none))
(define fd
(lx.timerfd-create CLOCK_REALTIME TFD_NONBLOCK))
(unwind-protect
(begin
;; 0.3 seconds = 300 ms = 300,000 us = 300,000,000 ns
(define nsecs 300000000)
;;; 9876543210
(lx.timerfd-settime fd 0
(lx.make-struct-itimerspec
;; one event every 0.3 seconds
(lx.make-struct-timespec 0 nsecs)
;; the first event after 1 nanosecond
(lx.make-struct-timespec 0 1)))
(printf "right after starting timer: ~a\n"
(lx.timerfd-read fd))
(px.nanosleep 1 0)
(printf "after 1 second: ~a\n"
(lx.timerfd-read fd))
(px.nanosleep 0 nsecs)
(printf "after 0.3 seconds: ~a\n"
(lx.timerfd-read fd)))
(px.close fd))
the output is:
right after starting timer: 1 after 1 second: 3 after 0.3 seconds: 1
we notice that right after starting the timer: the number of expirations
is 1 because the timer starts 1 nanosecond after the call
to timerfd-settime, which is almost immediately.
Previous: linux timerfd api, Up: linux timerfd [Index]