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