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 { 18 public: 19 20 FileDescriptor() = default; 21 FileDescriptor(const FileDescriptor&) = delete; 22 FileDescriptor& operator=(const FileDescriptor&) = delete; 23 FileDescriptor(FileDescriptor&&) = delete; 24 FileDescriptor& operator=(FileDescriptor&&) = delete; 25 26 /** 27 * Constructor 28 * 29 * @param[in] fd - File descriptor 30 */ 31 FileDescriptor(int fd) : fd(fd) 32 { 33 } 34 35 ~FileDescriptor() 36 { 37 if (fd >= 0) 38 { 39 close(fd); 40 } 41 } 42 43 int operator()() 44 { 45 return fd; 46 } 47 48 operator bool() const 49 { 50 return fd != -1; 51 } 52 53 void set(int descriptor) 54 { 55 if (fd >= 0) 56 { 57 close(fd); 58 } 59 60 fd = descriptor; 61 } 62 63 private: 64 65 /** 66 * File descriptor 67 */ 68 int fd = -1; 69 }; 70 71 } 72 } 73 } 74