0

I understand that a daemon should not write to stdout (and stderr) because that wouldn't be available once detached from the controlling terminal. But can I reopen stdout to a regular file, so that all my original logging will still work? This would be very nice and useful for me.

I tried something like this after forking,

freopen("/dev/null/", "r", stdin);
freopen("log", "w", stdout);
freopen("log", "w", stderr);

BOOST_LOG_TRIVIAL(info) << "daemonized!";

The daemon can be launched (to be precise, it doesn't fail and exit) and the log file can be created. But the log is empty (no "daemonized!"). Is this not the right way to daemonize? Could someone shed some light?

qweruiop
  • 3,156
  • 6
  • 31
  • 55
  • I think you have the reason back to front - if your `stdout` and/or `stderr` is going to a terminal, then it remains your controlling terminal and you fail to detach from it. Am I wrong? – Toby Speight Mar 10 '17 at 15:13

1 Answers1

0

There is a library function, daemon(int nochdir, int noclose), that is available to help code appropriately daemonize and additionally reopen the standard I/O streams connected to /dev/null. Using it and a system log facility (like syslog) would be the way I'd go insofar as a "right" way to daemonize.

Having the standard I/O streams open and associated with /dev/null would provide the benefit of avoiding any hiccups due to any left-over I/O with these (that might for example block the process or cause an unexpected signal). It'd additionally prevent any new descriptors from unsuspectingly acquiring them and unwittingly getting output from say left over printf statements.

As far as associating the standard I/O streams with a regular file, the following warning in the online daemonize program man page seems useful to recognize:

Be careful where you redirect the output! The file system containing the open file cannot be unmounted as long as the file is open. For best results, make sure that this output file is on the same file system as the daemon's working directory.

Louis Langholtz
  • 2,913
  • 3
  • 17
  • 40