From dba50eec49da55b7a50b066adbaeffc5d5a5cb3c Mon Sep 17 00:00:00 2001 From: Jim Meyering Date: Mon, 15 May 2000 10:21:25 +0000 Subject: (close_stdout_set_file_name): New function. (close_stdout_status): Use new file-scoped global. Return right away if fstat says the stdout file descriptor is invalid. --- lib/closeout.c | 44 +++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 41 insertions(+), 3 deletions(-) (limited to 'lib/closeout.c') diff --git a/lib/closeout.c b/lib/closeout.c index ed02a7df1..ac9904551 100644 --- a/lib/closeout.c +++ b/lib/closeout.c @@ -19,6 +19,9 @@ # include #endif +#include +#include + #if ENABLE_NLS # include # define _(Text) gettext (Text) @@ -33,16 +36,26 @@ # define EXIT_FAILURE 1 #endif +#if HAVE_UNISTD_H +# include +#endif + +#include + #include #ifndef errno extern int errno; #endif -#include +#ifndef STDOUT_FILENO +# define STDOUT_FILENO 1 +#endif + #include "closeout.h" #include "error.h" static int default_exit_status = EXIT_FAILURE; +static const char *file_name = NULL; /* Set the value to be used for the exit status when close_stdout is called. This is useful when it is not convenient to call close_stdout_status, @@ -53,6 +66,14 @@ close_stdout_set_status (int status) default_exit_status = status; } +/* Set the file name to be reported in the event an error is detected + by close_stdout_status. */ +void +close_stdout_set_file_name (const char *file) +{ + file_name = file; +} + /* Close standard output, exiting with status STATUS on failure. If a program writes *anything* to stdout, that program should `fflush' stdout and make sure that it succeeds before exiting. Otherwise, @@ -78,10 +99,27 @@ close_stdout_set_status (int status) void close_stdout_status (int status) { +#ifdef EBADF + struct stat sbuf; + if (fstat (STDOUT_FILENO, &sbuf) && errno == EBADF) + return; +#endif + if (ferror (stdout)) - error (status, 0, _("write error")); + { + if (file_name) + error (status, 0, _("%s: write error"), file_name); + else + error (status, 0, _("write error")); + } + if (fclose (stdout) != 0) - error (status, errno, _("write error")); + { + if (file_name) + error (status, errno, _("%s: write error"), file_name); + else + error (status, errno, _("write error")); + } } /* Close standard output, exiting with status EXIT_FAILURE on failure. */ -- cgit v1.2.3-54-g00ecf