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 | ||
238fab71 JG |
8 | #ifndef LTTNG_FILE_DESCRIPTOR_HPP |
9 | #define LTTNG_FILE_DESCRIPTOR_HPP | |
10 | ||
57b90af7 JG |
11 | #include <common/error.hpp> |
12 | #include <common/format.hpp> | |
13 | ||
14 | #include <algorithm> | |
15 | ||
16 | #include <unistd.h> | |
17 | ||
18 | namespace lttng { | |
19 | ||
20 | /* | |
21 | * RAII wrapper around a UNIX file descriptor. A file_descriptor's underlying | |
053c50e3 | 22 | * file descriptor. |
57b90af7 JG |
23 | */ |
24 | class file_descriptor { | |
25 | public: | |
b37c4851 JG |
26 | file_descriptor() |
27 | { | |
28 | } | |
29 | ||
30 | explicit file_descriptor(int raw_fd) noexcept : _raw_fd{ raw_fd } | |
57b90af7 JG |
31 | { |
32 | LTTNG_ASSERT(_is_valid_fd(_raw_fd)); | |
33 | } | |
34 | ||
35 | file_descriptor(const file_descriptor&) = delete; | |
9d89db29 | 36 | file_descriptor& operator=(const file_descriptor&) = delete; |
b37c4851 JG |
37 | file_descriptor& operator=(file_descriptor&& other) |
38 | { | |
39 | _cleanup(); | |
40 | std::swap(_raw_fd, other._raw_fd); | |
41 | return *this; | |
42 | } | |
57b90af7 | 43 | |
e9a2bd79 JG |
44 | file_descriptor(file_descriptor&& other) noexcept |
45 | { | |
57b90af7 JG |
46 | std::swap(_raw_fd, other._raw_fd); |
47 | } | |
48 | ||
49 | ~file_descriptor() | |
50 | { | |
b37c4851 | 51 | _cleanup(); |
57b90af7 JG |
52 | } |
53 | ||
54 | int fd() const noexcept | |
55 | { | |
56 | LTTNG_ASSERT(_is_valid_fd(_raw_fd)); | |
57 | return _raw_fd; | |
58 | } | |
59 | ||
60 | private: | |
61 | static bool _is_valid_fd(int fd) | |
62 | { | |
63 | return fd >= 0; | |
64 | } | |
65 | ||
b37c4851 JG |
66 | void _cleanup() |
67 | { | |
68 | if (!_is_valid_fd(_raw_fd)) { | |
69 | return; | |
70 | } | |
71 | ||
72 | const auto ret = ::close(_raw_fd); | |
73 | ||
74 | _raw_fd = -1; | |
75 | if (ret) { | |
76 | PERROR("Failed to close file descriptor: fd=%i", _raw_fd); | |
77 | } | |
78 | } | |
79 | ||
cd9adb8b | 80 | int _raw_fd = -1; |
57b90af7 JG |
81 | }; |
82 | ||
88277a52 | 83 | } /* namespace lttng */ |
238fab71 JG |
84 | |
85 | #endif /* LTTNG_FILE_DESCRIPTOR_HPP */ |