| 1 |
#include <errno.h> |
| 2 |
#ifdef HAVE_ERROR_H |
| 3 |
# include <error.h> |
| 4 |
#endif |
| 5 |
#ifdef HAVE_STDIO_EXT_H |
| 6 |
# include <stdio_ext.h> |
| 7 |
#else |
| 8 |
/* FIXME: use a more portable definition of __fpending() (from gnulib?) */ |
| 9 |
# include <stdio.h> |
| 10 |
# define __fpending(fp) ((fp)->_p - (fp)->_bf._base) |
| 11 |
#endif |
| 12 |
#include <stdlib.h> |
| 13 |
#include <unistd.h> |
| 14 |
|
| 15 |
#include "nls.h" |
| 16 |
#include "fileutils.h" |
| 17 |
#ifndef HAVE_ERROR_H |
| 18 |
# include "c.h" /* for error() emulation */ |
| 19 |
#endif |
| 20 |
|
| 21 |
int close_stream(FILE * stream) |
| 22 |
{ |
| 23 |
const int some_pending = (__fpending(stream) != 0); |
| 24 |
const int prev_fail = (ferror(stream) != 0); |
| 25 |
const int fclose_fail = (fclose(stream) != 0); |
| 26 |
if (prev_fail || (fclose_fail && (some_pending || errno != EBADF))) { |
| 27 |
if (!fclose_fail && errno != EPIPE) |
| 28 |
errno = 0; |
| 29 |
return EOF; |
| 30 |
} |
| 31 |
return 0; |
| 32 |
} |
| 33 |
|
| 34 |
/* Use atexit(); */ |
| 35 |
void close_stdout(void) |
| 36 |
{ |
| 37 |
if (close_stream(stdout) != 0 && !(errno == EPIPE)) { |
| 38 |
char const *write_error = _("write error"); |
| 39 |
error(0, errno, "%s", write_error); |
| 40 |
_exit(EXIT_FAILURE); |
| 41 |
} |
| 42 |
|
| 43 |
if (close_stream(stderr) != 0) |
| 44 |
_exit(EXIT_FAILURE); |
| 45 |
} |