I need to close stdout and stderr for one of my C program. How is it possible without exiting the program in execution?
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:
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.FILE*
pointers. Specifically:
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.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.