Why is STDIN open by default for programs running in SystemD?

73 views Asked by At

I have an if-statement at the top of a C main method, which checks if STDIN is open. If it is open, the program prints an error and exits. This is mainly for documentation reasons. I don't want users of the program to assume passing things to STDIN is supported.

A problem arose when I tried to execute this program as a SystemD daemon, however.

It seems like SystemD programs always have an open STDIN pipe.

Why is this? Can it be avoided?

2

There are 2 answers

10
ikegami On BEST ANSWER

It's kinda bad if fd 0 isn't opened because the next open would result in fd 0 being used. It's therefore common to have it open, but reading from /dev/null.

0
Chris Dodd On

When a daemon is started on pretty much any POSIX-style system, it will have fds 0 (stdin) and 1 (stdout) connected to /dev/null (fd 2 (stderr) may be connected to /dev/null or maybe to some logging service)

It's pretty much required to have them open, since leaving them closed would result in the next call that returned a new descriptor returning one of these -- POSIX requires that any new file descriptor always be allocated to the lowest index that is not currently open: POSIX File Descriptor Allocation.


If you expect some program to always be started as a daemon, it may make sense to ensure that stdin and stdout are not connected to any tty device (use isatty(3) for this).