blob: 54b98fce45114187d72bef52b686d2880a156fce [file] [log] [blame]
Matt Spinleree7adb72017-08-21 15:17:19 -05001#pragma once
2
3#include <unistd.h>
4namespace witherspoon
5{
6namespace power
7{
8namespace util
9{
10
11/**
12 * @class FileDescriptor
13 *
14 * Closes the file descriptor on destruction
15 */
16class FileDescriptor
17{
Matt Spinlerf0f02b92018-10-25 16:12:43 -050018 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 Spinleree7adb72017-08-21 15:17:19 -050024
Matt Spinlerf0f02b92018-10-25 16:12:43 -050025 /**
26 * Constructor
27 *
28 * @param[in] fd - File descriptor
29 */
Patrick Williamsb7ed5772023-05-10 07:50:45 -050030 FileDescriptor(int fd) : fd(fd) {}
Matt Spinleree7adb72017-08-21 15:17:19 -050031
Matt Spinlerf0f02b92018-10-25 16:12:43 -050032 ~FileDescriptor()
33 {
34 if (fd >= 0)
Matt Spinleree7adb72017-08-21 15:17:19 -050035 {
Matt Spinlerf0f02b92018-10-25 16:12:43 -050036 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 Spinleree7adb72017-08-21 15:17:19 -050055 }
56
Matt Spinlerf0f02b92018-10-25 16:12:43 -050057 fd = descriptor;
58 }
Matt Spinleree7adb72017-08-21 15:17:19 -050059
Matt Spinlerf0f02b92018-10-25 16:12:43 -050060 private:
61 /**
62 * File descriptor
63 */
64 int fd = -1;
Matt Spinleree7adb72017-08-21 15:17:19 -050065};
66
Matt Spinlerf0f02b92018-10-25 16:12:43 -050067} // namespace util
68} // namespace power
69} // namespace witherspoon