Commit | Line | Data |
---|---|---|
57b90af7 JG |
1 | /* |
2 | * Copyright (C) 2023 Jérémie Galarneau <jeremie.galarneau@efficios.com> | |
3 | * | |
4 | * SPDX-License-Identifier: LGPL-2.1-only | |
5 | * | |
6 | */ | |
7 | ||
8 | #include <common/error.hpp> | |
9 | #include <common/format.hpp> | |
10 | ||
11 | #include <algorithm> | |
12 | ||
13 | #include <unistd.h> | |
14 | ||
15 | namespace lttng { | |
16 | ||
17 | /* | |
18 | * RAII wrapper around a UNIX file descriptor. A file_descriptor's underlying | |
053c50e3 | 19 | * file descriptor. |
57b90af7 JG |
20 | */ |
21 | class file_descriptor { | |
22 | public: | |
b37c4851 JG |
23 | file_descriptor() |
24 | { | |
25 | } | |
26 | ||
27 | explicit file_descriptor(int raw_fd) noexcept : _raw_fd{ raw_fd } | |
57b90af7 JG |
28 | { |
29 | LTTNG_ASSERT(_is_valid_fd(_raw_fd)); | |
30 | } | |
31 | ||
32 | file_descriptor(const file_descriptor&) = delete; | |
9d89db29 | 33 | file_descriptor& operator=(const file_descriptor&) = delete; |
b37c4851 JG |
34 | file_descriptor& operator=(file_descriptor&& other) |
35 | { | |
36 | _cleanup(); | |
37 | std::swap(_raw_fd, other._raw_fd); | |
38 | return *this; | |
39 | } | |
57b90af7 | 40 | |
e9a2bd79 JG |
41 | file_descriptor(file_descriptor&& other) noexcept |
42 | { | |
57b90af7 JG |
43 | std::swap(_raw_fd, other._raw_fd); |
44 | } | |
45 | ||
46 | ~file_descriptor() | |
47 | { | |
b37c4851 | 48 | _cleanup(); |
57b90af7 JG |
49 | } |
50 | ||
51 | int fd() const noexcept | |
52 | { | |
53 | LTTNG_ASSERT(_is_valid_fd(_raw_fd)); | |
54 | return _raw_fd; | |
55 | } | |
56 | ||
57 | private: | |
58 | static bool _is_valid_fd(int fd) | |
59 | { | |
60 | return fd >= 0; | |
61 | } | |
62 | ||
b37c4851 JG |
63 | void _cleanup() |
64 | { | |
65 | if (!_is_valid_fd(_raw_fd)) { | |
66 | return; | |
67 | } | |
68 | ||
69 | const auto ret = ::close(_raw_fd); | |
70 | ||
71 | _raw_fd = -1; | |
72 | if (ret) { | |
73 | PERROR("Failed to close file descriptor: fd=%i", _raw_fd); | |
74 | } | |
75 | } | |
76 | ||
cd9adb8b | 77 | int _raw_fd = -1; |
57b90af7 JG |
78 | }; |
79 | ||
88277a52 | 80 | } /* namespace lttng */ |