File: test_compat-cloexec.c

package info (click to toggle)
rrdtool 1.9.0-2.1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 4,772 kB
  • sloc: ansic: 39,371; sh: 1,810; perl: 1,268; cs: 652; makefile: 573; python: 169; ruby: 61; awk: 30
file content (69 lines) | stat: -rw-r--r-- 1,276 bytes parent folder | download
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <compat-cloexec.h>

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#ifdef _POSIX_C_SOURCE
#  include <fcntl.h>
#else
#  define O_RDONLY	0
#  define O_RDWR	0
#  define O_APPEND	0
#endif

static void fail(char *msg, int line)
{
	fprintf(stderr, "%s:%u %s\n", __FILE__, line, msg);
	abort();
}

static void check_file(FILE *f, int exp_flags, bool is_cloexec, int line)
{
	int		flags;
	int		fd;

	if (!f)
		fail("fopen() failed", line);

#ifndef _POSIX_C_SOURCE
	(void)flags;
	(void)fd;
	(void)exp_flags;
	(void)is_cloexec;
#else
	fd = fileno(f);
	if (fd < 0)
		fail("failed to get fd", line);

	flags = fcntl(fd, F_GETFD);

	if (O_CLOEXEC != 0) {
		if (is_cloexec != (((flags & FD_CLOEXEC) != 0)))
			fail("O_CLOEXEC mismatch", line);
	}

	flags = fcntl(fd, F_GETFL);
	flags &= (O_RDONLY | O_WRONLY | O_RDWR | O_APPEND);
	if (flags != exp_flags)
		fail("flag mismatch", line);
#endif

	fclose(f);
}

int main(void) {
	FILE *f;

	f = _rrd_fopen("/dev/null", "r");
	check_file(f, O_RDONLY, false, __LINE__);

	f = _rrd_fopen("/dev/null", "re");
	check_file(f, O_RDONLY, true, __LINE__);

	f = _rrd_fopen("/dev/null", "w+be");
	check_file(f, O_RDWR, true, __LINE__);

	f = _rrd_fopen("/dev/null", "a+be");
	check_file(f, O_RDWR | O_APPEND, true, __LINE__);
}