Skip to content

Instantly share code, notes, and snippets.

@inscapist
Forked from mrnugget/about.md
Created September 7, 2024 14:59
Show Gist options
  • Save inscapist/02490d11d539fac3d0a590fe1b1554d8 to your computer and use it in GitHub Desktop.
Save inscapist/02490d11d539fac3d0a590fe1b1554d8 to your computer and use it in GitHub Desktop.
The self-pipe trick in Ruby
#!/usr/bin/env ruby
# Contrived example of self-pipe preventing signal race condition prior to select()
# @see http://cr.yp.to/docs/selfpipe.html
# @author Paul Annesley
SELF_READ, SELF_WRITE = IO.pipe
@run = true
trap :INT do
@run = false
SELF_WRITE.putc(0)
end
# send SIGINT mid-sleep
Process.fork { sleep 1; Process.kill :INT, Process.ppid; exit }
r,w = IO.pipe
while @run do
sleep 0.2 # .. amplify race-condition; exists until select()
w.putc(".") if @run # .. nothing written if SIGINT handler has disabled @run
selected = IO.select [r, SELF_READ]
break if selected.first.include? SELF_READ
print r.getc
end
puts 'without self-pipe, select() would have blocked'
@inscapist
Copy link
Author

sleep 0.2 might be sleep 2 instead to be accurate?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment