blob: e23c3cea9e23df8fad81d9f4ebdc1299d6a94f08 [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 */
30 FileDescriptor(int fd) : fd(fd)
Patrick Williams2c4fbc42020-06-26 15:33:11 -050031 {}
Matt Spinleree7adb72017-08-21 15:17:19 -050032
Matt Spinlerf0f02b92018-10-25 16:12:43 -050033 ~FileDescriptor()
34 {
35 if (fd >= 0)
Matt Spinleree7adb72017-08-21 15:17:19 -050036 {
Matt Spinlerf0f02b92018-10-25 16:12:43 -050037 close(fd);
38 }
39 }
40
41 int operator()()
42 {
43 return fd;
44 }
45
46 operator bool() const
47 {
48 return fd != -1;
49 }
50
51 void set(int descriptor)
52 {
53 if (fd >= 0)
54 {
55 close(fd);
Matt Spinleree7adb72017-08-21 15:17:19 -050056 }
57
Matt Spinlerf0f02b92018-10-25 16:12:43 -050058 fd = descriptor;
59 }
Matt Spinleree7adb72017-08-21 15:17:19 -050060
Matt Spinlerf0f02b92018-10-25 16:12:43 -050061 private:
62 /**
63 * File descriptor
64 */
65 int fd = -1;
Matt Spinleree7adb72017-08-21 15:17:19 -050066};
67
Matt Spinlerf0f02b92018-10-25 16:12:43 -050068} // namespace util
69} // namespace power
70} // namespace witherspoon