bigbiff bigbiff | e60683a | 2013-02-22 20:55:50 -0500 | [diff] [blame] | 1 | #ifndef UTIL_LINUX_CLOSESTREAM_H |
| 2 | #define UTIL_LINUX_CLOSESTREAM_H |
| 3 | |
| 4 | #include <stdio.h> |
| 5 | #ifdef HAVE_STDIO_EXT_H |
| 6 | #include <stdio_ext.h> |
| 7 | #endif |
| 8 | #include <unistd.h> |
| 9 | |
| 10 | #include "c.h" |
| 11 | #include "nls.h" |
| 12 | |
| 13 | #ifndef HAVE___FPENDING |
| 14 | static inline int |
| 15 | __fpending(FILE *stream __attribute__((__unused__))) |
| 16 | { |
| 17 | return 0; |
| 18 | } |
| 19 | #endif |
| 20 | |
| 21 | static inline int |
| 22 | close_stream(FILE * stream) |
| 23 | { |
| 24 | const int some_pending = (__fpending(stream) != 0); |
| 25 | const int prev_fail = (ferror(stream) != 0); |
| 26 | const int fclose_fail = (fclose(stream) != 0); |
bigbiff | 7b4c7a6 | 2015-01-01 19:44:14 -0500 | [diff] [blame] | 27 | |
bigbiff bigbiff | e60683a | 2013-02-22 20:55:50 -0500 | [diff] [blame] | 28 | if (prev_fail || (fclose_fail && (some_pending || errno != EBADF))) { |
bigbiff | 7b4c7a6 | 2015-01-01 19:44:14 -0500 | [diff] [blame] | 29 | if (!fclose_fail && !(errno == EPIPE)) |
bigbiff bigbiff | e60683a | 2013-02-22 20:55:50 -0500 | [diff] [blame] | 30 | errno = 0; |
| 31 | return EOF; |
| 32 | } |
| 33 | return 0; |
| 34 | } |
| 35 | |
| 36 | /* Meant to be used atexit(close_stdout); */ |
| 37 | static inline void |
| 38 | close_stdout(void) |
| 39 | { |
| 40 | if (close_stream(stdout) != 0 && !(errno == EPIPE)) { |
| 41 | if (errno) |
| 42 | warn(_("write error")); |
| 43 | else |
| 44 | warnx(_("write error")); |
| 45 | _exit(EXIT_FAILURE); |
| 46 | } |
| 47 | |
| 48 | if (close_stream(stderr) != 0) |
| 49 | _exit(EXIT_FAILURE); |
| 50 | } |
| 51 | |
bigbiff | 7b4c7a6 | 2015-01-01 19:44:14 -0500 | [diff] [blame] | 52 | #ifndef HAVE_FSYNC |
| 53 | static inline int |
| 54 | fsync(int fd __attribute__((__unused__))) |
| 55 | { |
| 56 | return 0; |
| 57 | } |
| 58 | #endif |
| 59 | |
| 60 | static inline int |
| 61 | close_fd(int fd) |
| 62 | { |
| 63 | const int fsync_fail = (fsync(fd) != 0); |
| 64 | const int close_fail = (close(fd) != 0); |
| 65 | |
| 66 | if (fsync_fail || close_fail) |
| 67 | return EOF; |
| 68 | return 0; |
| 69 | } |
| 70 | |
bigbiff bigbiff | e60683a | 2013-02-22 20:55:50 -0500 | [diff] [blame] | 71 | #endif /* UTIL_LINUX_CLOSESTREAM_H */ |