ahoward (owner)

Revisions

gist: 227679 Download_button fork
public
Public Clone URL: git://gist.github.com/227679.git
Embed All Files: show embed
Ruby #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
    class LifeLine
#--{{{
      FDS = ThreadSafeHash.new
 
      def initialize
        @pair = Socket.pair Socket::AF_UNIX, Socket::SOCK_STREAM, 0
        @owner = Process.pid
        @pid = nil
        @socket = nil
        @object_id = object_id
 
        @fds = @pair.map{|s| s.fileno}
        oid, fds = @object_id, @fds
        FDS[oid] = fds
        ObjectSpace.define_finalizer(self){ FDS.delete oid }
      end
 
      def owner?
        Process.pid == @owner
      end
 
      def throw *ignored
        raise unless owner?
        @pair[-1].close
        @pair[-1] = nil
        @pid = Process.pid
        @socket = @pair[0]
        @socket.sync = true
      end
 
      def catch *ignored
        raise if owner?
        @pair[0].close
        @pair[0] = nil
        @pid = Process.pid
        @socket = @pair[-1]
        @socket.sync = true
        close_unused_sockets_after_forking
      end
 
      def close_unused_sockets_after_forking
        begin
          to_delete = []
          begin
            FDS.each do |oid, fds|
              next if oid == @object_id
              begin
                IO.for_fd(fds.first).close
              rescue Exception => e
                STDERR.puts "#{ e.message } (#{ e.class })\n#{ e.backtrace.join 10.chr }"
              ensure
                to_delete << oid
              end
            end
          ensure
            FDS.ex{ to_delete.each{|oid| FDS.delete oid rescue 42} }
          end
          GC.start
        rescue Exception => e
          42
        end
      end