Is close/fclose on stdin guaranteed to be correct?

Greg Rogers picture Greg Rogers · Nov 13, 2008 · Viewed 14.5k times · Source

It seems as though the following calls do what you'd expect (close the stream and not allow any further input - anything waiting for input on the stream returns error), but is it guaranteed to be correct across all compilers/platforms?

close(fileno(stdin));
fclose(stdin);

Answer

fclose(stdin) causes any further use of stdin (implicit or explicit) to invoke undefined behavior, which is a very bad thing. It does not "inhibit input".

close(fileno(stdin)) causes any further attempts at input from stdin, after the current buffer has been depleted, to fail with EBADF, but only until you open another file, in which case that file will become fd #0 and bad things will happen.

A more robust approach might be:

int fd = open("/dev/null", O_WRONLY);
dup2(fd, 0);
close(fd);

with a few added error checks. This will ensure that all reads (after the current buffer is depleted) result in errors. If you just want them to result in EOF, not an error, use O_RDONLY instead of O_WRONLY.