Skip to content

Instantly share code, notes, and snippets.

@Eyal-Shalev
Last active December 18, 2019 12:36
Show Gist options
  • Save Eyal-Shalev/679bce73ad97a6e2e209e0f693bc0797 to your computer and use it in GitHub Desktop.
Save Eyal-Shalev/679bce73ad97a6e2e209e0f693bc0797 to your computer and use it in GitHub Desktop.
ruby fiber fork
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