I wonder why uncommenting that the first printf statement in the following program changes its subsequent behavior:
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
int main() {
close(STDOUT_FILENO);
if (write(STDOUT_FILENO, "Direct write\n", 13) != 13)
fprintf(stderr, "Error on write after close(STDOUT_FILENO): %s\n", strerror(errno));
int rtn;
if ((rtn = printf("printf after close(STDOUT_FILENO)\n")) < 0 || ferror(stdout))
fprintf(stderr, "Error on printf after close(STDOUT_FILENO)\n");
fprintf(stderr, "printf returned %d\n", rtn);
if (fflush(stdout) || ferror(stdout))
fprintf(stderr, "Error on fflush(stdout): %s\n", strerror(errno));
}
Without this first printf, subsequent printf rtns 34, as if an error had not occurred, even if the connection from the user stdout buffer to the underlying fd was closed. Only on manual fflush (stdout) error message is returned. But the first time printf is turned on, the next printf reports errors that I expect. Of course, nothing is written to the terminal (via printf) after STDOUT_FILENO fd has been closed anyway.
close(STDOUT_FILENO) ; , , -, , - .
Linux gcc.