Last active
December 18, 2019 12:36
-
-
Save Eyal-Shalev/679bce73ad97a6e2e209e0f693bc0797 to your computer and use it in GitHub Desktop.
ruby fiber fork
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'eventmachine' | |
require 'em-synchrony' | |
fiber_fork = ->(cmd) { | |
f = Fiber.current | |
Fiber.new { | |
reader, writer = IO.pipe | |
fork { | |
reader.close | |
writer.write(`#{cmd}`) | |
writer.close | |
} | |
writer.close | |
data = '' | |
while true do | |
begin | |
data << reader.read_nonblock(1024) | |
rescue EOFError | |
break | |
rescue IO::WaitReadable | |
EM::Synchrony.interrupt | |
end | |
end | |
f.resume data | |
}.resume | |
Fiber.yield | |
} | |
EM.run do | |
Fiber.new { | |
(1..10).each { |i| | |
p [:sleeping, i] | |
EM::Synchrony.sleep 1 | |
} | |
}.resume | |
EM.synchrony do | |
puts fiber_fork.('sleep 10; echo "foo"') | |
EM.stop | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment