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