2012-04-04 12:22:08 -05:00
|
|
|
#ifndef UTIL_LINUX_CLOSESTREAM_H
|
|
|
|
#define UTIL_LINUX_CLOSESTREAM_H
|
|
|
|
|
|
|
|
#include <stdio.h>
|
2012-04-23 07:26:23 -05:00
|
|
|
#ifdef HAVE_STDIO_EXT_H
|
2012-04-04 12:22:08 -05:00
|
|
|
#include <stdio_ext.h>
|
2012-04-23 07:26:23 -05:00
|
|
|
#endif
|
2012-04-04 12:22:08 -05:00
|
|
|
#include <unistd.h>
|
|
|
|
|
|
|
|
#include "c.h"
|
|
|
|
#include "nls.h"
|
|
|
|
|
2016-08-16 06:35:06 -05:00
|
|
|
#ifndef CLOSE_EXIT_CODE
|
|
|
|
# define CLOSE_EXIT_CODE EXIT_FAILURE
|
|
|
|
#endif
|
|
|
|
|
2012-04-23 07:26:23 -05:00
|
|
|
#ifndef HAVE___FPENDING
|
|
|
|
static inline int
|
|
|
|
__fpending(FILE *stream __attribute__((__unused__)))
|
|
|
|
{
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
#endif
|
|
|
|
|
2012-04-04 12:22:08 -05:00
|
|
|
static inline int
|
|
|
|
close_stream(FILE * stream)
|
|
|
|
{
|
|
|
|
const int some_pending = (__fpending(stream) != 0);
|
|
|
|
const int prev_fail = (ferror(stream) != 0);
|
|
|
|
const int fclose_fail = (fclose(stream) != 0);
|
2014-03-13 06:41:03 -05:00
|
|
|
|
2012-04-04 12:22:08 -05:00
|
|
|
if (prev_fail || (fclose_fail && (some_pending || errno != EBADF))) {
|
2014-03-13 06:41:03 -05:00
|
|
|
if (!fclose_fail && !(errno == EPIPE))
|
2012-04-04 12:22:08 -05:00
|
|
|
errno = 0;
|
|
|
|
return EOF;
|
|
|
|
}
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
/* Meant to be used atexit(close_stdout); */
|
|
|
|
static inline void
|
|
|
|
close_stdout(void)
|
|
|
|
{
|
|
|
|
if (close_stream(stdout) != 0 && !(errno == EPIPE)) {
|
|
|
|
if (errno)
|
|
|
|
warn(_("write error"));
|
|
|
|
else
|
|
|
|
warnx(_("write error"));
|
2016-08-16 06:35:06 -05:00
|
|
|
_exit(CLOSE_EXIT_CODE);
|
2012-04-04 12:22:08 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
if (close_stream(stderr) != 0)
|
2016-08-16 06:35:06 -05:00
|
|
|
_exit(CLOSE_EXIT_CODE);
|
2012-04-04 12:22:08 -05:00
|
|
|
}
|
|
|
|
|
2013-04-13 14:54:44 -05:00
|
|
|
#ifndef HAVE_FSYNC
|
|
|
|
static inline int
|
|
|
|
fsync(int fd __attribute__((__unused__)))
|
|
|
|
{
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
#endif
|
|
|
|
|
|
|
|
static inline int
|
|
|
|
close_fd(int fd)
|
|
|
|
{
|
|
|
|
const int fsync_fail = (fsync(fd) != 0);
|
|
|
|
const int close_fail = (close(fd) != 0);
|
|
|
|
|
|
|
|
if (fsync_fail || close_fail)
|
|
|
|
return EOF;
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
2012-04-04 12:22:08 -05:00
|
|
|
#endif /* UTIL_LINUX_CLOSESTREAM_H */
|