blob: bd5265716e749fa58cb29b3c0526f1c20143fa3b [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
brians343bc112013-02-10 01:53:46 +00004namespace aos {
5
6// Smart "pointer" (container) for a file descriptor.
7class ScopedFD {
8 public:
9 explicit ScopedFD(int fd = -1) : fd_(fd) {}
Austin Schuh56c5cf52022-12-25 22:20:40 -080010 ScopedFD(ScopedFD &) = delete;
11 ScopedFD(ScopedFD &&other) : ScopedFD(other.release()) {}
12
13 void operator=(const ScopedFD &) = delete;
14 void operator=(ScopedFD &&other) {
15 int tmp = fd_;
16 fd_ = other.fd_;
17 other.fd_ = tmp;
18 }
19
Parker Schuh2cd173d2017-01-28 00:12:01 -080020 ~ScopedFD() { Close(); }
Austin Schuh56c5cf52022-12-25 22:20:40 -080021
brians343bc112013-02-10 01:53:46 +000022 int get() const { return fd_; }
23 int release() {
24 const int r = fd_;
25 fd_ = -1;
26 return r;
27 }
28 void reset(int new_fd = -1) {
29 if (fd_ != new_fd) {
30 Close();
31 fd_ = new_fd;
32 }
33 }
Maxwell Hendersonb963ffc2024-02-02 21:55:04 -080034 explicit operator bool() const { return fd_ != -1; }
Parker Schuh2cd173d2017-01-28 00:12:01 -080035
brians343bc112013-02-10 01:53:46 +000036 private:
37 int fd_;
Austin Schuh56c5cf52022-12-25 22:20:40 -080038
Brian Silverman58899fd2019-03-24 11:03:11 -070039 void Close();
brians343bc112013-02-10 01:53:46 +000040};
41
42} // namespace aos
Parker Schuh2cd173d2017-01-28 00:12:01 -080043
Brian Silverman58899fd2019-03-24 11:03:11 -070044#endif // AOS_SCOPED_SCOPED_FD_H_