1 #ifndef ANDROID_DVR_EPOLL_FILE_DESCRIPTOR_H_
2 #define ANDROID_DVR_EPOLL_FILE_DESCRIPTOR_H_
3 
4 #include <android-base/unique_fd.h>
5 #include <log/log.h>
6 #include <sys/epoll.h>
7 
8 namespace android {
9 namespace dvr {
10 
11 class EpollFileDescriptor {
12  public:
13   static const int CTL_ADD = EPOLL_CTL_ADD;
14   static const int CTL_MOD = EPOLL_CTL_MOD;
15   static const int CTL_DEL = EPOLL_CTL_DEL;
16 
EpollFileDescriptor()17   EpollFileDescriptor() : fd_(-1) {}
18 
19   // Constructs an EpollFileDescriptor from an integer file descriptor and
20   // takes ownership.
EpollFileDescriptor(int fd)21   explicit EpollFileDescriptor(int fd) : fd_(fd) {}
22 
IsValid()23   bool IsValid() const { return fd_.get() >= 0; }
24 
Create()25   int Create() {
26     if (IsValid()) {
27       ALOGW("epoll fd has already been created.");
28       return -EALREADY;
29     }
30 
31     fd_.reset(epoll_create1(EPOLL_CLOEXEC));
32 
33     if (fd_.get() < 0)
34       return -errno;
35     else
36       return 0;
37   }
38 
Control(int op,int target_fd,epoll_event * ev)39   int Control(int op, int target_fd, epoll_event* ev) {
40     if (epoll_ctl(fd_.get(), op, target_fd, ev) < 0)
41       return -errno;
42     else
43       return 0;
44   }
45 
Wait(epoll_event * events,int maxevents,int timeout)46   int Wait(epoll_event* events, int maxevents, int timeout) {
47     int ret = epoll_wait(fd_.get(), events, maxevents, timeout);
48 
49     if (ret < 0)
50       return -errno;
51     else
52       return ret;
53   }
54 
Get()55   int Get() const { return fd_.get(); }
56 
57  private:
58   base::unique_fd fd_;
59 };
60 
61 }  // namespace dvr
62 }  // namespace android
63 
64 #endif  // ANDROID_DVR_EPOLL_FILE_DESCRIPTOR_H_
65