Why is it necessary to close standard input / output / error when recording a daemon?

Why is it necessary to close standard input / output / error when writing a daemon (unix)?

+4
source share
2 answers

You do not have to close the standard output / error, but you must be sure where your daemon (and child) is going to write. Redirecting output to a log file is common practice.

Closing the standard input is required so that the daemon (and / or the child) does not get stuck trying to read any input from the user.

But if you are going to disconnect the daemon from the control TTY using setsid() , standard input / output / error will be invalid.

+4
source

Not only stdin, stdout and stderr should be closed, but all open files.

From "Advanced UNIX Programming," W. Richard Stevens, Addison-Weseley, 18th Printing, 1999, p. 417.

Urgent file descriptors must be closed. This prevents the daemon from accessing any descriptors that it may have inherited from its parent (which may be a shell or some other process).

Mr. Stevens' suggestion is to get the maximum file descriptor and close all files to this value.

The cited chapter is devoted to "The processes of the demon." Note that closing file descriptors is only one in five points when writing daemons.

+6
source

Source: https://habr.com/ru/post/1402800/


All Articles