Advertisement
Guest User

Untitled

a guest
Dec 7th, 2011
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.67 KB | None | 0 0
  1. #!/usr/bin/env ruby
  2.  
  3. # Contrived example of self-pipe preventing signal race condition prior to select()
  4. # @see http://cr.yp.to/docs/selfpipe.html
  5. # @author Paul Annesley
  6.  
  7. SELF_READ, SELF_WRITE = IO.pipe
  8. @run = true
  9.  
  10. trap :INT do
  11. @run = false
  12. SELF_WRITE.putc(0)
  13. end
  14.  
  15. # send SIGINT mid-sleep
  16. Process.fork { sleep 1; Process.kill :INT, Process.ppid; exit }
  17.  
  18. r,w = IO.pipe
  19. while @run do
  20. sleep 0.2 # .. amplify race-condition; exists until select()
  21. w.putc(".") if @run # .. nothing written if SIGINT handler has disabled @run
  22. selected = IO.select [r, SELF_READ]
  23. break if selected.first.include? SELF_READ
  24. print r.getc
  25. end
  26.  
  27. puts 'without self-pipe, select() would have blocked'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement