开发者

Talking with a Ruby daemonized process

开发者 https://www.devze.com 2023-01-21 23:30 出处:网络
I use Ruby 1.9 and the following method inside my program: Process.daemon Then, when I open a new terminal, I would like to call my daemonized program (named my_program) and send to it a message. S

I use Ruby 1.9 and the following method inside my program:

Process.daemon

Then, when I open a new terminal, I would like to call my daemonized program (named my_program) and send to it a message. Such as this:

$ my_p开发者_如何学运维rogram --are_you_still_alive

Thank you for any idea.


you could use signals to determine if the program is still alive

Signal.trap("USR1") do
  puts "I'm alive"
end

then you call

$ kill -USR1 $(pidof my_program)


There are several ways to do IPC (inter-process communication). One way is sending signals as @lukstei is showing is his answer. Another way is by using sockets, here is a minimal example of a daemon that you can ask for the time using TCP sockets:

#!/usr/bin/env ruby -wKU

require 'socket'

case ARGV[0]
when "start"
  puts "start daemon"
  server = TCPServer.open('0.0.0.0', 9090)
  Process.daemon
  loop {
    conn = server.accept
    conn.puts "Hello !"
    conn.puts "Time is #{Time.now}"
    conn.close    
  }
when "time?"
  puts "Asking daemon what time it is"
  sock = TCPSocket.open('0.0.0.0', 9090)
  while line = sock.gets
    puts line
  end
  sock.close
end

Let's try it out:

$ ./my_daemon.rb start
start daemon
$ ./my_daemon.rb time?
Asking daemon what time it is
Hello !
Time is 2013-10-25 17:01:32 +0200
$ ./my_daemon.rb time?
Asking daemon what time it is
Hello !
Time is 2013-10-25 17:01:34 +0200

Hope this helps!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号