blob: d762012bc463b4fc83a7bfefd909ff1ab77a83a3 [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)
31 {
32 }
Matt Spinleree7adb72017-08-21 15:17:19 -050033
Matt Spinlerf0f02b92018-10-25 16:12:43 -050034 ~FileDescriptor()
35 {
36 if (fd >= 0)
Matt Spinleree7adb72017-08-21 15:17:19 -050037 {
Matt Spinlerf0f02b92018-10-25 16:12:43 -050038 close(fd);
39 }
40 }
41
42 int operator()()
43 {
44 return fd;
45 }
46
47 operator bool() const
48 {
49 return fd != -1;
50 }
51
52 void set(int descriptor)
53 {
54 if (fd >= 0)
55 {
56 close(fd);
Matt Spinleree7adb72017-08-21 15:17:19 -050057 }
58
Matt Spinlerf0f02b92018-10-25 16:12:43 -050059 fd = descriptor;
60 }
Matt Spinleree7adb72017-08-21 15:17:19 -050061
Matt Spinlerf0f02b92018-10-25 16:12:43 -050062 private:
63 /**
64 * File descriptor
65 */
66 int fd = -1;
Matt Spinleree7adb72017-08-21 15:17:19 -050067};
68
Matt Spinlerf0f02b92018-10-25 16:12:43 -050069} // namespace util
70} // namespace power
71} // namespace witherspoon