blob: 696cf3b6f3419747d3dd408822c7dab394a8e41c [file] [log] [blame]
John Park33858a32018-09-28 23:05:48 -07001#ifndef _AOS_SCOPED_FD_
2#define _AOS_SCOPED_FD_
Parker Schuh2cd173d2017-01-28 00:12:01 -08003
Brian Silverman8efe23e2013-07-07 23:31:37 -07004#include <unistd.h>
5
John Park33858a32018-09-28 23:05:48 -07006#include "aos/logging/logging.h"
7#include "aos/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
John Park33858a32018-09-28 23:05:48 -070044#endif // _AOS_SCOPED_FD_