Matt Spinler | ee7adb7 | 2017-08-21 15:17:19 -0500 | [diff] [blame] | 1 | #pragma once |
2 | |||||
3 | #include <unistd.h> | ||||
Lei YU | ab09332 | 2019-10-09 16:43:22 +0800 | [diff] [blame] | 4 | namespace phosphor |
Matt Spinler | ee7adb7 | 2017-08-21 15:17:19 -0500 | [diff] [blame] | 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 | { | ||||
Matt Spinler | f0f02b9 | 2018-10-25 16:12:43 -0500 | [diff] [blame] | 18 | 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 Spinler | ee7adb7 | 2017-08-21 15:17:19 -0500 | [diff] [blame] | 24 | |
Matt Spinler | f0f02b9 | 2018-10-25 16:12:43 -0500 | [diff] [blame] | 25 | /** |
26 | * Constructor | ||||
27 | * | ||||
28 | * @param[in] fd - File descriptor | ||||
29 | */ | ||||
30 | FileDescriptor(int fd) : fd(fd) | ||||
31 | { | ||||
32 | } | ||||
Matt Spinler | ee7adb7 | 2017-08-21 15:17:19 -0500 | [diff] [blame] | 33 | |
Matt Spinler | f0f02b9 | 2018-10-25 16:12:43 -0500 | [diff] [blame] | 34 | ~FileDescriptor() |
35 | { | ||||
36 | if (fd >= 0) | ||||
Matt Spinler | ee7adb7 | 2017-08-21 15:17:19 -0500 | [diff] [blame] | 37 | { |
Matt Spinler | f0f02b9 | 2018-10-25 16:12:43 -0500 | [diff] [blame] | 38 | 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 Spinler | ee7adb7 | 2017-08-21 15:17:19 -0500 | [diff] [blame] | 57 | } |
58 | |||||
Matt Spinler | f0f02b9 | 2018-10-25 16:12:43 -0500 | [diff] [blame] | 59 | fd = descriptor; |
60 | } | ||||
Matt Spinler | ee7adb7 | 2017-08-21 15:17:19 -0500 | [diff] [blame] | 61 | |
Matt Spinler | f0f02b9 | 2018-10-25 16:12:43 -0500 | [diff] [blame] | 62 | private: |
63 | /** | ||||
64 | * File descriptor | ||||
65 | */ | ||||
66 | int fd = -1; | ||||
Matt Spinler | ee7adb7 | 2017-08-21 15:17:19 -0500 | [diff] [blame] | 67 | }; |
68 | |||||
Matt Spinler | f0f02b9 | 2018-10-25 16:12:43 -0500 | [diff] [blame] | 69 | } // namespace util |
70 | } // namespace power | ||||
Lei YU | ab09332 | 2019-10-09 16:43:22 +0800 | [diff] [blame] | 71 | } // namespace phosphor |