daemons icon indicating copy to clipboard operation
daemons copied to clipboard

call_as_daemon method don't stop child process

Open sada opened this issue 9 months ago • 2 comments

Your environment

  • ruby -v: ruby 3.2.2 (2023-03-30 revision e51014f9c0) [x86_64-linux]
  • daemons (1.4.1)

Describe the bug

Calling Process.waitpid inside the at_exit method will prevent the child process from stopping.

To Reproduce

Script:

Gemfile

# frozen_string_literal: true

source "https://rubygems.org"

gem "daemons"

test_daemon.rb

#!/usr/bin/env ruby

require 'bundler/setup'
Bundler.setup
require 'daemons'

at_exit do
  begin
    Process.waitpid
  rescue Errno::ESRCH, Errno::ECHILD
  end
end

2.times do |i|
  Daemons.run_proc("test_daemon.#{i}") do
    loop do
    end
  end
end

Terminal:

$ test_daemon.rb start

Child process doesn't stop.

$ ps aux
--snip--
sada     14719  1.8  0.2 177232 37168 pts/6    Sl+  17:01   0:00 ruby ./test_daemon.rb start
sada     14735  0.0  0.2 177232 33832 ?        Ssl  17:01   0:00 ruby ./test_daemon.rb start
sada     14737 94.6  0.2 180308 37540 ?        Rl   17:01   0:08 test_daemon.0

The following fork operations are no longer possible.

  1. Forks another child process and exits first child. This prevents the potential of acquiring a controlling terminal.

https://github.com/thuehlinger/daemons/blob/a0e84bcebe8b872ff59e1e0aa10e1f1718a933b1/lib/daemons.rb#L43-L51

By the way, I encountered this problem when using delayed_job and debug.

Expected behavior

Child processes can be stopped. Since the first child process should be stopped, I thought it would be a good idea to change the call to the exit! method.

https://github.com/thuehlinger/daemons/blob/a0e84bcebe8b872ff59e1e0aa10e1f1718a933b1/lib/daemons/daemonize.rb#L67

sada avatar Apr 30 '24 04:04 sada