blob: 7596db1be6edcee788f2c57184358e5479877745 [file] [log] [blame]
Murulidhar Nataraju06a0c2c2017-07-11 08:55:33 -05001#pragma once
2
3#include <unistd.h>
Patrick Ventureda79c9c2018-11-01 15:35:52 -07004
5#include <sstream>
6
Murulidhar Nataraju06a0c2c2017-07-11 08:55:33 -05007namespace openpower
8{
9namespace sbe
10{
11namespace internal
12{
13
14/** @class FileDescriptor
15 * @brief Provide RAII file descriptor
16 */
17class FileDescriptor
18{
Patrick Ventureda79c9c2018-11-01 15:35:52 -070019 private:
20 /** @brief File descriptor for the SBE FIFO device */
21 int fd = -1;
Murulidhar Nataraju06a0c2c2017-07-11 08:55:33 -050022
Patrick Ventureda79c9c2018-11-01 15:35:52 -070023 public:
24 FileDescriptor() = delete;
25 FileDescriptor(const FileDescriptor&) = delete;
26 FileDescriptor& operator=(const FileDescriptor&) = delete;
27 FileDescriptor(FileDescriptor&&) = delete;
28 FileDescriptor& operator=(FileDescriptor&&) = delete;
Murulidhar Nataraju06a0c2c2017-07-11 08:55:33 -050029
Patrick Ventureda79c9c2018-11-01 15:35:52 -070030 /** @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 */
35 FileDescriptor(const char* devPath, int accessModes)
36 {
37 fd = open(devPath, accessModes);
38 if (fd < 0)
Murulidhar Nataraju06a0c2c2017-07-11 08:55:33 -050039 {
Patrick Ventureda79c9c2018-11-01 15:35:52 -070040 // 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());
Murulidhar Nataraju06a0c2c2017-07-11 08:55:33 -050046 }
Patrick Ventureda79c9c2018-11-01 15:35:52 -070047 }
Murulidhar Nataraju06a0c2c2017-07-11 08:55:33 -050048
Patrick Ventureda79c9c2018-11-01 15:35:52 -070049 /** @brief Saves File descriptor and uses it to do file operation
50 *
51 * @param[in] fd - File descriptor
52 */
53 FileDescriptor(int fd) : fd(fd)
54 {
55 // Nothing
56 }
57
58 ~FileDescriptor()
59 {
60 if (fd >= 0)
Murulidhar Nataraju06a0c2c2017-07-11 08:55:33 -050061 {
Patrick Ventureda79c9c2018-11-01 15:35:52 -070062 close(fd);
Murulidhar Nataraju06a0c2c2017-07-11 08:55:33 -050063 }
Patrick Ventureda79c9c2018-11-01 15:35:52 -070064 }
Murulidhar Nataraju06a0c2c2017-07-11 08:55:33 -050065
Patrick Ventureda79c9c2018-11-01 15:35:52 -070066 int operator()()
67 {
68 return fd;
69 }
Murulidhar Nataraju06a0c2c2017-07-11 08:55:33 -050070};
71
72} // namespace internal
73} // namespace sbe
74} // namespace openpower