Brian Silverman | 8efe23e | 2013-07-07 23:31:37 -0700 | [diff] [blame^] | 1 | #include <unistd.h> |
| 2 | |
brians | 343bc11 | 2013-02-10 01:53:46 +0000 | [diff] [blame] | 3 | #include "aos/common/macros.h" |
Brian Silverman | 598800f | 2013-05-09 17:08:42 -0700 | [diff] [blame] | 4 | #include "aos/common/logging/logging.h" |
brians | 343bc11 | 2013-02-10 01:53:46 +0000 | [diff] [blame] | 5 | |
| 6 | namespace aos { |
| 7 | |
| 8 | // Smart "pointer" (container) for a file descriptor. |
| 9 | class ScopedFD { |
| 10 | public: |
| 11 | explicit ScopedFD(int fd = -1) : fd_(fd) {} |
| 12 | ~ScopedFD() { |
| 13 | Close(); |
| 14 | } |
| 15 | int get() const { return fd_; } |
| 16 | int release() { |
| 17 | const int r = fd_; |
| 18 | fd_ = -1; |
| 19 | return r; |
| 20 | } |
| 21 | void reset(int new_fd = -1) { |
| 22 | if (fd_ != new_fd) { |
| 23 | Close(); |
| 24 | fd_ = new_fd; |
| 25 | } |
| 26 | } |
| 27 | operator bool() const { return fd_ != -1; } |
| 28 | private: |
| 29 | int fd_; |
| 30 | void Close() { |
| 31 | if (fd_ != -1) { |
| 32 | if (close(fd_) == -1) { |
| 33 | LOG(WARNING, "close(%d) failed with %d: %s\n", fd_, |
| 34 | errno, strerror(errno)); |
| 35 | } |
| 36 | } |
| 37 | } |
| 38 | DISALLOW_COPY_AND_ASSIGN(ScopedFD); |
| 39 | }; |
| 40 | |
| 41 | } // namespace aos |