Skip to content

Instantly share code, notes, and snippets.

Last active November 1, 2020 05:09
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
The self-pipe trick in Ruby
#!/usr/bin/env ruby
# Contrived example of self-pipe preventing signal race condition prior to select()
# @see
# @author Paul Annesley
@run = true
trap :INT do
@run = false
# 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 = [r, SELF_READ]
break if selected.first.include? SELF_READ
print r.getc
puts 'without self-pipe, select() would have blocked'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment