thuehlinger / daemons

Ruby daemons gem official repository
MIT License
648 stars 71 forks source link

Run script files in background (as daemons) #64

Closed viperey closed 6 years ago

viperey commented 6 years ago

Hi.

For some reason I'm not fully understanding the usage of the library for some cases. My use case is the following:

What's the better approach to achieve this behavior?

Example code:

require 'daemons'
require_relative 'parser.rb'

def get_config(index = 0)
  name = 'worker' + rand(0..Time.now.to_i).to_s
  script_argv_array = [
      '--my_named_arg', 'my_named_arg_value'
  ]
  daemon_argv_array = ['start', '--']
  argv_array = daemon_argv_array.concat script_argv_array
  {
      :app_name => name,
      :ARGV => argv_array,
      :dir => '/tmp',
      :dir_mode => :normal,
      :force => true,
      :mode => :load,
      :multiple => true,
      :name => name
  }
end

1.times do |index|
  config = get_config(index)
  puts("config=#{config}")
  begin
    process = Daemons.run(script = __dir__ + '/infinite_loop.rb', options = config)
    puts("process=#{process}")
  rescue Exception => e
    puts(e.to_s)
    puts(e.message)
    puts(e.backtrace)
    break
  end
  puts("Done")
end

puts("Scheduler is done")

I.e. This example code would throw an exception and child processes won't get PPID=1

Thanks in advance and congratulations for the library :)

thuehlinger commented 6 years ago

For your application it would probalby be easiest if you called your script just using e.g. system() and then within the script require 'daemons.rb'and then call Daemons.daemonize(). This way, the child script is detached from the parent process.

viperey commented 6 years ago

Oh, cool then it seems it was using the wrong design approach. Thanks for the advice!