Skip to content

Instantly share code, notes, and snippets.

@sorah
Created July 6, 2015 10:31
Show Gist options
  • Save sorah/ec2c316b00007e5c331b to your computer and use it in GitHub Desktop.
Save sorah/ec2c316b00007e5c331b to your computer and use it in GitHub Desktop.

daemon scripts (example)

(▰╹◡╹) time ruby daemon.rb
daemon: bye
daemon: bye (stderr)
ruby daemon.rb  0.08s user 0.04s system 2% cpu 5.136 total
(▰╹◡╹) time ruby daemon-starter.rb
loop 0
loop 1
start
started 93847
ruby daemon-starter.rb  0.08s user 0.04s system 5% cpu 2.141 total
(▰╹◡╹) daemon: bye
daemon: bye (stderr)

run.rb waits IO EOF, so it waits grandchild

(▰╹◡╹) time ruby run.rb
94129
#<Process::Status: pid 94129 exit 0>
daemon: bye (stderr)
"loop 0\nloop 1\nstart\nstarted 94139\ndaemon: bye\n"
ruby run.rb  0.15s user 0.05s system 2% cpu 7.292 total

run2.rb reads child output progressive, and quits when the first child exited

(▰╹◡╹) time ruby run2.rb
94350
"loop 0\nloop 1\nstart\n"
"started 94351\n"
ruby run2.rb  0.15s user 0.04s system 8% cpu 2.215 total
(▰╹◡╹) daemon: bye (stderr)
(▰╹◡╹)
2.times do |x|
puts "loop #{x}"
sleep 1
end
puts "start"
pid = spawn("ruby", "daemon.rb")
puts "started #{pid}"
sleep 5
puts "daemon: bye"
$stderr.puts "daemon: bye (stderr)"
exit
Dir.chdir File.dirname(__FILE__)
child_i, child_o = IO.pipe
pid = spawn("ruby", "./daemon-starter.rb", out: child_o, err: $stderr)
p pid
child_o.close
pid, stat = Process.waitpid2(pid)
p stat
p child_i.read
Dir.chdir File.dirname(__FILE__)
begin
quit_i, quit_o = IO.pipe
child_i, child_o = IO.pipe
th = Thread.new do
begin
loop do
readable_ios, = IO.select([quit_i, child_i])
if readable_ios.include?(child_i)
p child_i.read_nonblock(1000)
end
if readable_ios.include?(quit_i)
p :th_quit
break
end
end
rescue EOFError
p :th_quit_eof
ensure
quit_i.close unless quit_i.closed?
child_i.close unless child_i.closed?
end
end
th.abort_on_exception = true
pid = spawn("ruby", "./daemon-starter.rb", out: child_o, err: $stderr)
p pid
child_o.close
pid, stat = Process.waitpid2(pid)
begin
quit_o.syswrite 1
rescue Errno::EPIPE
end
ensure
quit_o.close
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment