blob: e393e8948c15545a2025236720b8273090b9d9b1 [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) {}
Austin Schuh56c5cf52022-12-25 22:20:40 -080014 ScopedFD(ScopedFD &) = delete;
15 ScopedFD(ScopedFD &&other) : ScopedFD(other.release()) {}
16
17 void operator=(const ScopedFD &) = delete;
18 void operator=(ScopedFD &&other) {
19 int tmp = fd_;
20 fd_ = other.fd_;
21 other.fd_ = tmp;
22 }
23
Parker Schuh2cd173d2017-01-28 00:12:01 -080024 ~ScopedFD() { Close(); }
Austin Schuh56c5cf52022-12-25 22:20:40 -080025
brians343bc112013-02-10 01:53:46 +000026 int get() const { return fd_; }
27 int release() {
28 const int r = fd_;
29 fd_ = -1;
30 return r;
31 }
32 void reset(int new_fd = -1) {
33 if (fd_ != new_fd) {
34 Close();
35 fd_ = new_fd;
36 }
37 }
Maxwell Hendersonb963ffc2024-02-02 21:55:04 -080038 explicit operator bool() const { return fd_ != -1; }
Parker Schuh2cd173d2017-01-28 00:12:01 -080039
brians343bc112013-02-10 01:53:46 +000040 private:
41 int fd_;
Austin Schuh56c5cf52022-12-25 22:20:40 -080042
Brian Silverman58899fd2019-03-24 11:03:11 -070043 void Close();
brians343bc112013-02-10 01:53:46 +000044};
45
46} // namespace aos
Parker Schuh2cd173d2017-01-28 00:12:01 -080047
Brian Silverman58899fd2019-03-24 11:03:11 -070048#endif // AOS_SCOPED_SCOPED_FD_H_