Project

General

Profile

Feature #2250 ยป io-finalize.rb

pilcrow (Mike Pomraning), 10/22/2009 12:43 PM

 
1
#!/usr/bin/env ruby
2

    
3
require 'socket'
4
require 'iosyssocket' # Adds IO::syssocket(), IO::sysclose()
5

    
6
include Socket::Constants
7

    
8
FIN = proc { |id| puts "Finalizing an IO::for_fd() object..." }
9

    
10
begin
11
  #
12
  # 1. Simulate an extension library which uses sockets internally,
13
  #    exposing an fd to the ruby layer for for_fd()
14
  #
15
  [ IO.syssocket(AF_INET, SOCK_STREAM, 0) ].each do |fd|
16
    io = IO.for_fd(fd)
17
    ObjectSpace.define_finalizer(io, FIN)
18
    #
19
    # 2. here we'd probably Kernel.select( [io], ... ), etc. ...
20
    #
21
    IO.sysclose(fd) # 3. extension library cleans itself up
22
  end
23
end
24

    
25
dev_null = File.new("/dev/null") # 4. We re-use the fd our library just closed
26

    
27
p dev_null.stat # 5. Which appears quite normal, until ...
28
GC.start
29
p dev_null.stat # 6. ... the IO::for_fd() object finalizer closes it!
30
                #        Errno::EBADF