| 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 |
| 19 | * file descriptor |
| 20 | */ |
| 21 | class file_descriptor { |
| 22 | public: |
| 23 | explicit file_descriptor(int raw_fd) noexcept : _raw_fd{raw_fd} |
| 24 | { |
| 25 | LTTNG_ASSERT(_is_valid_fd(_raw_fd)); |
| 26 | } |
| 27 | |
| 28 | file_descriptor(const file_descriptor&) = delete; |
| 29 | file_descriptor& operator=(const file_descriptor&) = delete; |
| 30 | file_descriptor& operator=(file_descriptor&&) = delete; |
| 31 | |
| 32 | file_descriptor(file_descriptor&& other) noexcept { |
| 33 | LTTNG_ASSERT(_is_valid_fd(_raw_fd)); |
| 34 | std::swap(_raw_fd, other._raw_fd); |
| 35 | } |
| 36 | |
| 37 | ~file_descriptor() |
| 38 | { |
| 39 | if (!_is_valid_fd(_raw_fd)) { |
| 40 | return; |
| 41 | } |
| 42 | |
| 43 | const auto ret = ::close(_raw_fd); |
| 44 | if (ret) { |
| 45 | PERROR("Failed to close file descriptor: fd=%i", _raw_fd); |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | int fd() const noexcept |
| 50 | { |
| 51 | LTTNG_ASSERT(_is_valid_fd(_raw_fd)); |
| 52 | return _raw_fd; |
| 53 | } |
| 54 | |
| 55 | private: |
| 56 | static bool _is_valid_fd(int fd) |
| 57 | { |
| 58 | return fd >= 0; |
| 59 | } |
| 60 | |
| 61 | int _raw_fd = -1; |
| 62 | }; |
| 63 | |
| 64 | } /* namespace lttng */ |