vendredi 24 juillet 2015

How do you stop forked (child) processes using the daemons gem for ruby?

I'm using the daemons gem in a RoR application to open tcp ports to get syslogs from infrastructure hosts. Upon stopping the daemon my tcp ports stay open. I'm using fork to start the new processes while adding the pids from fork into an array to use when the while loop stops to kill the child processes. I'm not having success killing the processes.

Here is the daemon script:

#!/usr/bin/env ruby
require 'socket'
require '../lib/logsvr_assets/logsvr'

require File.dirname(__FILE__) + '/../config/environment'

$running = true
Signal.trap('TERM') do
  $running = false
end

pids = []

while $running do
  loop do
    hosts = LogsvrConfig.all
    hosts.each { |host|
      protocol = host.logsvr_protocol.name.to_s
      port = host.port.to_s
      msg_type = host.logsvr_msg_type.name.to_s
      tag = host.tag.to_s
      host_addr = host.host_addr.to_s
      begin
        is_available = TCPServer.open(port.to_i)
        if is_available
          is_available.close
          pids << fork {
            Logsvr.svr(protocol,
                       port,
                       msg_type,
                       tag,
                       host_addr)
          }
        end
      rescue Errno::EADDRINUSE
        sleep(10)
      end
    }
  end
end

pids.each { |pid|
  begin
    Process.kill(9,pid)
  rescue Errno::ESRCH => e
    puts(e)
  end
}

Aucun commentaire:

Enregistrer un commentaire