blob: e654d3d15a1741c0a0ba76f4d4bb7cfb7c8268db [file] [log] [blame]
brians343bc112013-02-10 01:53:46 +00001#include "aos/common/macros.h"
2
3namespace aos {
4
5// Smart "pointer" (container) for a file descriptor.
6class ScopedFD {
7 public:
8 explicit ScopedFD(int fd = -1) : fd_(fd) {}
9 ~ScopedFD() {
10 Close();
11 }
12 int get() const { return fd_; }
13 int release() {
14 const int r = fd_;
15 fd_ = -1;
16 return r;
17 }
18 void reset(int new_fd = -1) {
19 if (fd_ != new_fd) {
20 Close();
21 fd_ = new_fd;
22 }
23 }
24 operator bool() const { return fd_ != -1; }
25 private:
26 int fd_;
27 void Close() {
28 if (fd_ != -1) {
29 if (close(fd_) == -1) {
30 LOG(WARNING, "close(%d) failed with %d: %s\n", fd_,
31 errno, strerror(errno));
32 }
33 }
34 }
35 DISALLOW_COPY_AND_ASSIGN(ScopedFD);
36};
37
38} // namespace aos