4

Normally I can write logs with Logger:

//abc.rb
require 'logger'
logger = Logger.new('foo.log')

$./abc.rb

But in a Daemons I got a permission error:

//xyz.rb
require 'logger'
require 'daemons'

Daemons.run_proc('xyz') do
  logger = Logger.new('foo.log')
end

$./xyz.rb
/home/raincole/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/logger.rb:599:in `initialize': Permission denied - foo.log (Errno::EACCES)
from /home/raincole/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/logger.rb:599:in `open'
from /home/raincole/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/logger.rb:599:in `create_logfile'
from /home/raincole/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/logger.rb:594:in `open_logfile'
from /home/raincole/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/logger.rb:549:in `initialize'
from /home/raincole/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/logger.rb:314:in `new'
from /home/raincole/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/logger.rb:314:in `initialize'

I ran abc.rb and xyz.rb in the same directory and with the same identity. Why can't one log as the other can?

Lai Yu-Hsuan
  • 27,509
  • 28
  • 97
  • 164

1 Answers1

9

Here's the reason. From the Daemons documentation.

I have put in bold the relevant part for you:

What does daemons internally do with my daemons?

From a technical aspect of view, daemons does the following when creating a daemon:

  1. Forks a child (and exits the parent process, if needed)
  2. Becomes a session leader (which detaches the program from the controlling terminal).
  3. Forks another child process and exits first child. This prevents the potential of acquiring a controlling terminal.
  4. Changes the current working directory to "/".
  5. Clears the file creation mask (sets umask to 0000).
  6. Closes file descriptors (reopens STDOUT and STDERR to point to a logfile if possible).

So after you start the daemon you should either change your current working directory (Dir.chdir) to the directory you want to use for logging, or use absolute paths for your logfiles.

Casper
  • 33,403
  • 4
  • 84
  • 79
  • I don't recommend `chdir`. Daemons (and ideally all apps) should always use absolute paths. Accessing relative paths is usually a source of bugs. – Kelvin Jul 26 '13 at 19:03