Why is it necessary to redirect STDIN, STDOUT, STDERR to / dev / null when starting the daemon?

I saw in SO how to redirect STDIN, STDOUT, STDERR to / dev / null in C. This is done when the daemon starts. But why is it necessary to run the unix / linux daemon correctly?

Bonus question:

What happens if STDOUT closed and the file descriptor is used without reopening?

+7
c unix daemon
source share
2 answers

stdin , stdout and stderr are closed, so that the daemon can successfully disconnect from the tty from which it was launched, and also so that the daemon (or its child processes) does not write to tty when it is running.

If you try to read / write from a private file descriptor, the operation will fail and errno will be set to EBADF ("fildes is not a valid file or socket descriptor open for reading"). Other than that, nothing will happen.

+8
source share

TL; DR

You should not. It is not necessary to run the unix / linux daemon correctly. Always write log messages to stderr .

Bonus

errno set to EBADF if a private file descriptor is used and the operation fails.

Summary

Do not demonize your program within yourself. Use the daemon manager to demonstrate. (Remember? Do one and do it right.)

No matter what program you write, always go to stderr . This has the following advantages, and I quote Jonathan de Boyne Pollard :

  • The log output from your dæmon will automatically be completely separate from the log output of other users.
  • You do not need any additional files in the chroot () prison.
  • Log data will not be lost and will be recorded in the same order in which it was generated.
  • Other programs / people will not be able to embed spoof messages in the output file.

Redirecting stderr to /dev/null will be much more difficult for sysadmin to integrate your log into its systems. You can outrage them by doing the following: I quote Chris Jester Yang :

  • Insist on using syslog and do not provide any options for entering standard error or standard output.
  • To be sure, explicitly close file descriptors 1 and 2 or redirect them to / dev / null.

Link

0
source share

All Articles