blob: 29ccf6e0f610b35bd379114280df5b2687841e47 [file] [log] [blame]
Parker Schuh2cd173d2017-01-28 00:12:01 -08001#ifndef _AOS_COMMON_SCOPED_FD_
2#define _AOS_COMMON_SCOPED_FD_
3
Brian Silverman8efe23e2013-07-07 23:31:37 -07004#include <unistd.h>
5
Brian Silverman598800f2013-05-09 17:08:42 -07006#include "aos/common/logging/logging.h"
Parker Schuh2cd173d2017-01-28 00:12:01 -08007#include "aos/common/macros.h"
brians343bc112013-02-10 01:53:46 +00008
9namespace aos {
10
11// Smart "pointer" (container) for a file descriptor.
12class ScopedFD {
13 public:
14 explicit ScopedFD(int fd = -1) : fd_(fd) {}
Parker Schuh2cd173d2017-01-28 00:12:01 -080015 ~ScopedFD() { Close(); }
brians343bc112013-02-10 01:53:46 +000016 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 Schuh2cd173d2017-01-28 00:12:01 -080029
brians343bc112013-02-10 01:53:46 +000030 private:
31 int fd_;
32 void Close() {
33 if (fd_ != -1) {
34 if (close(fd_) == -1) {
Brian Silverman01be0002014-05-10 15:44:38 -070035 PLOG(WARNING, "close(%d) failed", fd_);
brians343bc112013-02-10 01:53:46 +000036 }
37 }
38 }
39 DISALLOW_COPY_AND_ASSIGN(ScopedFD);
40};
41
42} // namespace aos
Parker Schuh2cd173d2017-01-28 00:12:01 -080043
44#endif // _AOS_COMMON_SCOPED_FD_