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