summaryrefslogtreecommitdiff
path: root/lib/bsdutil/close_fd.h
blob: 68ba6c945d5b2050f04d1dcca98ca185ae9ebd7e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#ifndef _PATH_DEV
/*
 * The tailing '/' in _PATH_DEV is there for compatibility with libc.
 */
# define _PATH_DEV"/dev/"
#endif

////////////////////////////////////////////////
/// Cargo culted from util-linux include/c.h ///
////////////////////////////////////////////////
#include <err.h>

/*
 * Force a compilation error if condition is true, but also produce a
 * result (of value 0 and type size_t), so the expression can be used
 * e.g. in a structure initializer (or wherever else comma expressions
 * aren't permitted).
 */
#define UL_BUILD_BUG_ON_ZERO(e) __extension__ (sizeof(struct { int:-!!(e); }))
#define BUILD_BUG_ON_NULL(e) ((void *)sizeof(struct { int:-!!(e); }))

#ifdef __GNUC__
/* &a[0] degrades to a pointer: a different type from an array */
# define __must_be_array(a) \
	UL_BUILD_BUG_ON_ZERO(__builtin_types_compatible_p(__typeof__(a), __typeof__(&a[0])))

# define ignore_result(x) __extension__ ({ \
	__typeof__(x) __dummy __attribute__((__unused__)) = (x); (void) __dummy; \
		})
#else /* !__GNUC__ */
# define __must_be_array(a)     0
# define __attribute__(_arg_)
# define ignore_result(x) ((void) (x))
#endif /* !__GNUC__ */

#ifndef ARRAY_SIZE
# define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]) + __must_be_array(arr))
#endif

//////////////////////////////////////////////////////////
/// Cargo culted from util-linux include/closestream.h ///
//////////////////////////////////////////////////////////
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;
}