1 #pragma once 2 3 #include <unistd.h> 4 namespace openpower 5 { 6 namespace sbe 7 { 8 namespace internal 9 { 10 11 /** @class FileDescriptor 12 * @brief Provide RAII file descriptor 13 */ 14 class FileDescriptor 15 { 16 private: 17 /** @brief File descriptor for the SBE FIFO device */ 18 int fd = -1; 19 20 public: 21 FileDescriptor() = delete; 22 FileDescriptor(const FileDescriptor&) = delete; 23 FileDescriptor& operator=(const FileDescriptor&) = delete; 24 FileDescriptor(FileDescriptor&&) = delete; 25 FileDescriptor& operator=(FileDescriptor&&) = delete; 26 27 /** @brief Opens the input file and saves the file descriptor 28 * 29 * @param[in] devPath - Path of the file 30 * @para,[in] accessModes - File access modes 31 */ 32 FileDescriptor(const char* devPath, int accessModes) 33 { 34 fd = open(devPath, accessModes); 35 if (fd < 0) 36 { 37 //TODO:use elog infrastructure 38 std::ostringstream errMsg; 39 errMsg << "Opening the device with device path:" << 40 devPath << " and access modes:" << accessModes << 41 ",Failed with errno" << errno; 42 throw std::runtime_error(errMsg.str().c_str()); 43 } 44 45 } 46 47 /** @brief Saves File descriptor and uses it to do file operation 48 * 49 * @param[in] fd - File descriptor 50 */ 51 FileDescriptor(int fd) : fd(fd) 52 { 53 // Nothing 54 } 55 56 ~FileDescriptor() 57 { 58 if (fd >= 0) 59 { 60 close(fd); 61 } 62 } 63 64 int operator()() 65 { 66 return fd; 67 } 68 }; 69 70 } // namespace internal 71 } // namespace sbe 72 } // namespace openpower 73