blob: e098d2c0dda989e02f6e2527b8af48869d4e617c [file] [log] [blame]
Brian Silverman58899fd2019-03-24 11:03:11 -07001#ifndef AOS_SCOPED_SCOPED_FD_H_
2#define AOS_SCOPED_SCOPED_FD_H_
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/macros.h"
brians343bc112013-02-10 01:53:46 +00007
8namespace aos {
9
10// Smart "pointer" (container) for a file descriptor.
11class ScopedFD {
12 public:
13 explicit ScopedFD(int fd = -1) : fd_(fd) {}
Parker Schuh2cd173d2017-01-28 00:12:01 -080014 ~ScopedFD() { Close(); }
brians343bc112013-02-10 01:53:46 +000015 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; }
Parker Schuh2cd173d2017-01-28 00:12:01 -080028
brians343bc112013-02-10 01:53:46 +000029 private:
30 int fd_;
Brian Silverman58899fd2019-03-24 11:03:11 -070031 void Close();
brians343bc112013-02-10 01:53:46 +000032 DISALLOW_COPY_AND_ASSIGN(ScopedFD);
33};
34
35} // namespace aos
Parker Schuh2cd173d2017-01-28 00:12:01 -080036
Brian Silverman58899fd2019-03-24 11:03:11 -070037#endif // AOS_SCOPED_SCOPED_FD_H_