How to close stdout and stderr in C?

Usman picture Usman · Feb 11, 2011 · Viewed 34.2k times · Source

I need to close stdout and stderr for one of my C program. How is it possible without exiting the program in execution?

Answer

user257111 picture user257111 · Feb 11, 2011

You can just:

fclose(stdout);
fclose(stderr);

For anybody wondering why you might want to do this, this is a fairly common task for a daemon/service process on Unix.

However you should be aware that closing a file descriptor may have unintended consequences:

  • When you open new files these now free descriptors will be used. So, for example, if you subsequently fopen that file descriptor (on Linux, at least) will replace fd 1, i.e. stdout. Any code that subsequently uses this will write to this file, which may not be what you intended.
  • See R..'s comments on file descriptors versus C library FILE* pointers. Specifically:
    • If you write to a closed fd under Linux, you'll get an error, but:
    • If you use a C library function that uses stdout or stderr (which are FILE* pointers (see their definition) then writing to these whilst FILE* is closed is undefined behaviour. This will likely crash your program in unexpected ways, not always at the point of the bug either. See undefined behaviour.
  • Your code isn't the only part affected. Any libraries you use, and any processes you launch which inherited these file descriptors as their standard descriptors are also affected.

The quick, one-line solution is to freopen() To say /dev/null, /dev/console under Linux/OSX or nul on Windows. Alternatively, you can use your platform-specific implementation to re-open the file descriptors/handles as required.