| 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 | #ifndef LTTNG_FILE_DESCRIPTOR_HPP |
| 9 | #define LTTNG_FILE_DESCRIPTOR_HPP |
| 10 | |
| 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 |
| 22 | * file descriptor. |
| 23 | */ |
| 24 | class file_descriptor { |
| 25 | public: |
| 26 | file_descriptor() |
| 27 | { |
| 28 | } |
| 29 | |
| 30 | explicit file_descriptor(int raw_fd) noexcept : _raw_fd{ raw_fd } |
| 31 | { |
| 32 | LTTNG_ASSERT(_is_valid_fd(_raw_fd)); |
| 33 | } |
| 34 | |
| 35 | file_descriptor(const file_descriptor&) = delete; |
| 36 | file_descriptor& operator=(const file_descriptor&) = delete; |
| 37 | file_descriptor& operator=(file_descriptor&& other) |
| 38 | { |
| 39 | _cleanup(); |
| 40 | std::swap(_raw_fd, other._raw_fd); |
| 41 | return *this; |
| 42 | } |
| 43 | |
| 44 | file_descriptor(file_descriptor&& other) noexcept |
| 45 | { |
| 46 | std::swap(_raw_fd, other._raw_fd); |
| 47 | } |
| 48 | |
| 49 | ~file_descriptor() |
| 50 | { |
| 51 | _cleanup(); |
| 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 | |
| 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 | |
| 80 | int _raw_fd = -1; |
| 81 | }; |
| 82 | |
| 83 | } /* namespace lttng */ |
| 84 | |
| 85 | #endif /* LTTNG_FILE_DESCRIPTOR_HPP */ |