Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Add a test and @tmm1s patch for making post-fork EM.run calls work as…

… expected.

Closes #213
  • Loading branch information...
commit 427a76d270f796688bdeaa0bbe5c71414101cdbe 1 parent 8cd81fb
James Tucker authored September 29, 2011
11  lib/eventmachine.rb
@@ -155,7 +155,13 @@ def self.run blk=nil, tail=nil, &block
155 155
     # will start without release_machine being called and will immediately throw
156 156
 
157 157
     #
158  
-
  158
+    if reactor_running? and @reactor_pid != Process.pid
  159
+      # Reactor was started in a different parent, meaning we have forked.
  160
+      # Clean up reactor state so a new reactor boots up in this child.
  161
+      stop_event_loop
  162
+      release_machine
  163
+      @reactor_running = false
  164
+    end
159 165
 
160 166
     tail and @tails.unshift(tail)
161 167
 
@@ -169,6 +175,7 @@ def self.run blk=nil, tail=nil, &block
169 175
       @next_tick_queue ||= []
170 176
       @tails ||= []
171 177
       begin
  178
+        @reactor_pid = Process.pid
172 179
         @reactor_running = true
173 180
         initialize_event_machine
174 181
         (b = blk || block) and add_timer(0, b)
@@ -252,7 +259,7 @@ def self.fork_reactor &block
252 259
       if self.reactor_running?
253 260
         self.stop_event_loop
254 261
         self.release_machine
255  
-        self.instance_variable_set( '@reactor_running', false )
  262
+        @reactor_running = false
256 263
       end
257 264
       self.run block
258 265
     end
24  tests/test_basic.rb
@@ -245,4 +245,28 @@ def c.unbind
245 245
     assert !timer_ran
246 246
     assert_equal 1, num_close_scheduled
247 247
   end
  248
+
  249
+  def test_fork_safe
  250
+    return unless cpid = fork { exit! } rescue false
  251
+
  252
+    read, write = IO.pipe
  253
+    EM.run do
  254
+      cpid = fork do
  255
+        write.puts "forked"
  256
+        EM.run do
  257
+          EM.next_tick do
  258
+            write.puts "EM ran"
  259
+            exit!
  260
+          end
  261
+        end
  262
+      end
  263
+      EM.stop
  264
+    end
  265
+    Process.waitall
  266
+    assert_equal "forked\n", read.readline
  267
+    assert_equal "EM ran\n", read.readline
  268
+  ensure
  269
+    read.close rescue nil
  270
+    write.close rescue nil
  271
+  end
248 272
 end

0 notes on commit 427a76d

Please sign in to comment.
Something went wrong with that request. Please try again.