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?
CodePudding user response:
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.
CodePudding user response:
Closing file descriptors at application level is for error reporting purposes and to make some additional actions before exiting.
The default closing upon exit will not make the calling process return an error exit code and/or display an error message if the close operation fails. But the custom one embedded in the coreutils source code makes the calling process decide to report or not any error upon failures.
You can find close_stdout()
in the gnulib which contains the following in the header comment:
Close standard output. On error, issue a diagnostic and _exit with status 'exit_failure'.
[...]
It's important to detect such failures and exit nonzero because many tools (most notably 'make' and other build-management systems) depend on being able to detect failure in other tools via their exit status.