How to close stdout and stderr in C?
What have you tried? Doesn't fclose
work?
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
orstderr
(which areFILE*
pointers (see their definition) then writing to these whilstFILE*
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.