aboutsummaryrefslogtreecommitdiffstats
path: root/liblfjail/fd.hh
blob: f20acb8e9dd8f12f25350851d3fa5080880c6726 (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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/*
 * This source code is released into the public domain.
 */

/*
 * fd: a file descriptor.
 */

#ifndef	LFJAIL_FD_HH
#define	LFJAIL_FD_HH

#include <fcntl.h>
#include <unistd.h>

#include "generic_error.hh"

namespace lfjail {

struct fd final {
	// Construct an empty (invalid) fd.
	fd() noexcept = default;
	~fd();

	// Construct an fd by taking ownership of an exiting fd.
	fd(int fd_) noexcept;

	// Move from another fd, leaving the moved-from fd in an invalid state.
	fd(fd &&other) noexcept;

	auto operator=(fd &&other) noexcept -> fd &;

	// Not copyable.
	fd(fd const &) = delete;
	fd& operator=(fd const &) = delete;

	// Return true if this fd is valid (open).
	explicit operator bool(this fd const &self) noexcept;

	// Close the stored fd.  Errors are discarded.
	auto close(this fd &self) -> void;

	// Return the stored fd.
	auto get(this fd const &self) -> int;

	// Release the stored fd and return it.  The caller must close
	// the fd.
	auto release() && noexcept -> int;

private:
	static constexpr int _invalid_fd = -1;

	int _fd = _invalid_fd;
};

// Create a copy of this fd by calling dup().
auto dup(fd const &self) -> fd;

// Create a copy of this fd by calling dup2().  The second argument
// must not be managed by an instance of the fd class, or else it
// will be closed twice.
auto dup(fd const &self, int newfd) -> fd;

// Return the fnctl flags for this fd.
auto getflags(fd const &self) -> int;

// Replace the fnctl flags for this fd.
auto replaceflags(fd &self, int newflags) -> void;

// Add bits to the fcntl flags for this fd.
auto setflags(fd &self, int newflags) -> void;

// Remove bits from the fcntl flags for this fd.
auto clearflags(fd &self, int clrflags) -> void;

// Create two fds by calling pipe() and return them.
auto pipe() -> std::pair<fd, fd>;

} // namespace lfjail

#endif	// !LFJAIL_FD_HH