1 /* Close standard output and standard error, exiting with a diagnostic on error. 2 3 Copyright (C) 1998, 1999, 2000, 2001, 2002, 2004, 2006 Free 4 Software Foundation, Inc. 5 6 This program is free software; you can redistribute it and/or modify 7 it under the terms of the GNU General Public License as published by 8 the Free Software Foundation; either version 2, or (at your option) 9 any later version. 10 11 This program is distributed in the hope that it will be useful, 12 but WITHOUT ANY WARRANTY; without even the implied warranty of 13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 GNU General Public License for more details. 15 16 You should have received a copy of the GNU General Public License 17 along with this program; if not, write to the Free Software Foundation, 18 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ 19 20 #include <config.h> 21 22 #include "closeout.h" 23 24 #include <errno.h> 25 #include <stdio.h> 26 #include <unistd.h> 27 28 #include "gettext.h" 29 #define _(msgid) gettext (msgid) 30 31 #include "close-stream.h" 32 #include "error.h" 33 #include "exitfail.h" 34 #include "quotearg.h" 35 36 static const char *file_name; 37 38 /* Set the file name to be reported in the event an error is detected 39 by close_stdout. */ 40 void 41 close_stdout_set_file_name (const char *file) 42 { 43 file_name = file; 44 } 45 46 /* Close standard output. On error, issue a diagnostic and _exit 47 with status 'exit_failure'. 48 49 Also close standard error. On error, _exit with status 'exit_failure'. 50 51 Since close_stdout is commonly registered via 'atexit', POSIX 52 and the C standard both say that it should not call 'exit', 53 because the behavior is undefined if 'exit' is called more than 54 once. So it calls '_exit' instead of 'exit'. If close_stdout 55 is registered via atexit before other functions are registered, 56 the other functions can act before this _exit is invoked. 57 58 Applications that use close_stdout should flush any streams 59 other than stdout and stderr before exiting, since the call to 60 _exit will bypass other buffer flushing. Applications should 61 be flushing and closing other streams anyway, to check for I/O 62 errors. Also, applications should not use tmpfile, since _exit 63 can bypass the removal of these files. 64 65 It's important to detect such failures and exit nonzero because many 66 tools (most notably `make' and other build-management systems) depend 67 on being able to detect failure in other tools via their exit status. */ 68 69 void 70 close_stdout (void) 71 { 72 if (close_stream (stdout) != 0) 73 { 74 char const *write_error = _("write error"); 75 if (file_name) 76 error (0, errno, "%s: %s", quotearg_colon (file_name), 77 write_error); 78 else 79 error (0, errno, "%s", write_error); 80 81 _exit (exit_failure); 82 } 83 84 if (close_stream (stderr) != 0) 85 _exit (exit_failure); 86 }