blob: eb22f8048de726b1104c7790f9914154c7092994 [file] [log] [blame]
Brian Silverman8efe23e2013-07-07 23:31:37 -07001#include <unistd.h>
2
brians343bc112013-02-10 01:53:46 +00003#include "aos/common/macros.h"
Brian Silverman598800f2013-05-09 17:08:42 -07004#include "aos/common/logging/logging.h"
brians343bc112013-02-10 01:53:46 +00005
6namespace aos {
7
8// Smart "pointer" (container) for a file descriptor.
9class 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