blob: d61b83b5ec4c7da22abad642d3612943940000d8 [file] [log] [blame]
bigbiff bigbiffe60683a2013-02-22 20:55:50 -05001#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
14static inline int
15__fpending(FILE *stream __attribute__((__unused__)))
16{
17 return 0;
18}
19#endif
20
21static inline int
22close_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);
27 if (prev_fail || (fclose_fail && (some_pending || errno != EBADF))) {
28 if (!fclose_fail)
29 errno = 0;
30 return EOF;
31 }
32 return 0;
33}
34
35/* Meant to be used atexit(close_stdout); */
36static inline void
37close_stdout(void)
38{
39 if (close_stream(stdout) != 0 && !(errno == EPIPE)) {
40 if (errno)
41 warn(_("write error"));
42 else
43 warnx(_("write error"));
44 _exit(EXIT_FAILURE);
45 }
46
47 if (close_stream(stderr) != 0)
48 _exit(EXIT_FAILURE);
49}
50
51#endif /* UTIL_LINUX_CLOSESTREAM_H */