blob: 57ecdd8f66fe2c45600b28e37c751b52086e6e67 [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) {
Brian Silverman01be0002014-05-10 15:44:38 -070033 PLOG(WARNING, "close(%d) failed", fd_);
brians343bc112013-02-10 01:53:46 +000034 }
35 }
36 }
37 DISALLOW_COPY_AND_ASSIGN(ScopedFD);
38};
39
40} // namespace aos