Daemons is a nice gem for writing background processes. Just call Daemons.daemonize when you are ready to detach.


Daemons likes to change your working directory to /, for no clear reason. My file accesses were silently failing, and this was why. Also, you can use the :ontop => true key to help debug a daemonized program. :ontop keeps the process in the foreground and leaves STDERR attached to the console.

5 responses

  1. Changing the working directory to / or /tmp is recommended for two reasons. One is that in case of a crash, any core dumps are written to the working directory of the deceased process. But more importantly, the working directory of any running process is considered by the OS to be in use. Using something other than / could lead to problems unmounting parts of the file system without killing the daemon first.

  2. That makes sense. I guess core dumps in / are an advantage if you are writing kernel modules or something, which run as root.

    Unfortunately for Daemons, though, it means that if you use the :backtrace => true key to request a stack dump, it tries to write to the working directory, which is now /. Of course it doesn’t have permission, so the result is a completely silent failure.

    I like your idea of changing to /tmp/ better.

  3. Another good reason for the change to / is that it starts a new process, not a child process of the current process. The environment isn’t copied from the parent process.

  4. I think it starts the new process via a double fork{}, not as an entirely new process. So the environment is maintained.

    The main thing is that the silent failure surprised me. I am not trying to criticize the gem specifically; after all, I still use it.