Skip to content

Instantly share code, notes, and snippets.

@benweint
Last active May 12, 2016 08:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benweint/6692546 to your computer and use it in GitHub Desktop.
Save benweint/6692546 to your computer and use it in GitHub Desktop.
threads across fork Ruby demo
#!/usr/bin/env ruby
# Pass 'fork' as the first argument to use Process.fork, otherwise Process.daemon is used.
do_fork = (ARGV[0] == 'fork')
thread = Thread.new do
loop { sleep(1) }
end
puts "using Process.#{do_fork ? 'fork' : 'daemon'}"
puts "before pid = #{$$}, thread.alive? = #{thread.alive?.inspect}"
if do_fork
pid = Process.fork
if pid.nil?
puts "after in child, pid = #{$$}, thread.alive? = #{thread.alive?.inspect}"
else
puts "after in parent, pid = #{$$}, thread.alive? = #{thread.alive?.inspect}"
end
else
Process.daemon(true, true)
puts "after, pid = #{$$}, thread.alive? = #{thread.alive?.inspect}"
exit(0)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment