Stdio to terminal after closing (STDOUT_FILENO)

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() {
  //printf("hi from C \n");

  // Close underlying file descriptor:
  close(STDOUT_FILENO);

  if (write(STDOUT_FILENO, "Direct write\n", 13) != 13) // immediate error detected.
    fprintf(stderr, "Error on write after close(STDOUT_FILENO): %s\n", strerror(errno));

  // printf() calls continue fine, ferror(stdout) = 0 (but no write to terminal):
  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);
  // Only on fflush is error detected:
  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.

+4
1

strace , , stdio , fstat, , stdout - , stdout , - , stdout -. close(1); printf, fstat EBADF, 1 , , stdout .

8192 - stdout , .


printf, fstat(1, ...) , Glibc , stdout ; stdout -, , printf after close(STDOUT_FILENO)\n , , .

+4

Source: https://habr.com/ru/post/1677390/


All Articles