Skip to content

Instantly share code, notes, and snippets.

@parruda
Created April 9, 2020 11:50
Show Gist options
  • Save parruda/19f21fd812281f995c0f40d323912517 to your computer and use it in GitHub Desktop.
Save parruda/19f21fd812281f995c0f40d323912517 to your computer and use it in GitHub Desktop.
Alarm() on crystal lang
lib LibC
ITIMER_REAL = 0
ITIMER_VIRTUAL = 1
ITIMER_PROF = 2
struct Itimerval
it_interval : Timeval
it_value : Timeval
end
struct Timeval
tv_sec : Long
tv_usec : Int
end
fun setitimer(which : Int, new_value : Itimerval*, old_value : Itimerval*) : Int
fun getitimer(which : Int, curr_value : Itimerval*) : Int
end
# Call alarm() in 5 seconds, using real time timer (LibC::ITIMER_REAL)
value = LibC::Timeval.new(tv_sec: 5.seconds)
timer_value = LibC::Itimerval.new(it_value: value)
old_value = LibC::Itimerval.new # this is required by setitimer
LibC.setitimer(LibC::ITIMER_REAL, pointerof(timer_value), pointerof(old_value))
Signal::ALRM.trap do
raise "Timeout!"
end
sleep 10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment