Matt Spinler | ee7adb7 | 2017-08-21 15:17:19 -0500 | [diff] [blame] | 1 | #pragma once |
2 | |||||
3 | #include <unistd.h> | ||||
4 | namespace witherspoon | ||||
5 | { | ||||
6 | namespace power | ||||
7 | { | ||||
8 | namespace util | ||||
9 | { | ||||
10 | |||||
11 | /** | ||||
12 | * @class FileDescriptor | ||||
13 | * | ||||
14 | * Closes the file descriptor on destruction | ||||
15 | */ | ||||
16 | class FileDescriptor | ||||
17 | { | ||||
Matt Spinler | f0f02b9 | 2018-10-25 16:12:43 -0500 | [diff] [blame] | 18 | public: |
19 | FileDescriptor() = default; | ||||
20 | FileDescriptor(const FileDescriptor&) = delete; | ||||
21 | FileDescriptor& operator=(const FileDescriptor&) = delete; | ||||
22 | FileDescriptor(FileDescriptor&&) = delete; | ||||
23 | FileDescriptor& operator=(FileDescriptor&&) = delete; | ||||
Matt Spinler | ee7adb7 | 2017-08-21 15:17:19 -0500 | [diff] [blame] | 24 | |
Matt Spinler | f0f02b9 | 2018-10-25 16:12:43 -0500 | [diff] [blame] | 25 | /** |
26 | * Constructor | ||||
27 | * | ||||
28 | * @param[in] fd - File descriptor | ||||
29 | */ | ||||
Patrick Williams | b7ed577 | 2023-05-10 07:50:45 -0500 | [diff] [blame] | 30 | FileDescriptor(int fd) : fd(fd) {} |
Matt Spinler | ee7adb7 | 2017-08-21 15:17:19 -0500 | [diff] [blame] | 31 | |
Matt Spinler | f0f02b9 | 2018-10-25 16:12:43 -0500 | [diff] [blame] | 32 | ~FileDescriptor() |
33 | { | ||||
34 | if (fd >= 0) | ||||
Matt Spinler | ee7adb7 | 2017-08-21 15:17:19 -0500 | [diff] [blame] | 35 | { |
Matt Spinler | f0f02b9 | 2018-10-25 16:12:43 -0500 | [diff] [blame] | 36 | close(fd); |
37 | } | ||||
38 | } | ||||
39 | |||||
40 | int operator()() | ||||
41 | { | ||||
42 | return fd; | ||||
43 | } | ||||
44 | |||||
45 | operator bool() const | ||||
46 | { | ||||
47 | return fd != -1; | ||||
48 | } | ||||
49 | |||||
50 | void set(int descriptor) | ||||
51 | { | ||||
52 | if (fd >= 0) | ||||
53 | { | ||||
54 | close(fd); | ||||
Matt Spinler | ee7adb7 | 2017-08-21 15:17:19 -0500 | [diff] [blame] | 55 | } |
56 | |||||
Matt Spinler | f0f02b9 | 2018-10-25 16:12:43 -0500 | [diff] [blame] | 57 | fd = descriptor; |
58 | } | ||||
Matt Spinler | ee7adb7 | 2017-08-21 15:17:19 -0500 | [diff] [blame] | 59 | |
Matt Spinler | f0f02b9 | 2018-10-25 16:12:43 -0500 | [diff] [blame] | 60 | private: |
61 | /** | ||||
62 | * File descriptor | ||||
63 | */ | ||||
64 | int fd = -1; | ||||
Matt Spinler | ee7adb7 | 2017-08-21 15:17:19 -0500 | [diff] [blame] | 65 | }; |
66 | |||||
Matt Spinler | f0f02b9 | 2018-10-25 16:12:43 -0500 | [diff] [blame] | 67 | } // namespace util |
68 | } // namespace power | ||||
69 | } // namespace witherspoon |