cstdoutstdingnuatexit

Why tee implementation closes STDIN and STDOUT at exiting?


coreutils tee source code closes standard input and output upon exit:

int
main (int argc, char **argv)
{

   atexit (close_stdout);

   <......>

  ok = tee_files (argc - optind, &argv[optind]);
  if (close (STDIN_FILENO) != 0)
    die (EXIT_FAILURE, errno, "%s", _("standard input"));

  return ok ? EXIT_SUCCESS : EXIT_FAILURE;
}

I wonder if it is necessary to do that as when the tee program terminates, STDIN and STDOUT are automatically closed by process management.

Is this just a good coding practice or is there a use case?


Solution

  • Tee is used for logging, so it closes stdout so that the log file handle will not remain open or locked and it closes stdin so that the program or user feeding it through stdin will receive an error if they attempt to continue to write to tee, this way if the process exits or is forcibly closed by another process the logging throws an error.