gator: Version 5.19
[firefly-linux-kernel-4.4.55.git] / tools / gator / daemon / Monitor.cpp
1 /**
2  * Copyright (C) ARM Limited 2013-2014. All rights reserved.
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License version 2 as
6  * published by the Free Software Foundation.
7  */
8
9 #include "Monitor.h"
10
11 #include <errno.h>
12 #include <string.h>
13 #include <unistd.h>
14
15 #include "Logging.h"
16
17 Monitor::Monitor() : mFd(-1) {
18 }
19
20 Monitor::~Monitor() {
21         if (mFd >= 0) {
22                 ::close(mFd);
23         }
24 }
25
26 void Monitor::close() {
27         if (mFd >= 0) {
28                 ::close(mFd);
29                 mFd = -1;
30         }
31 }
32
33 bool Monitor::init() {
34         mFd = epoll_create(16);
35         if (mFd < 0) {
36                 logg->logMessage("%s(%s:%i): epoll_create1 failed", __FUNCTION__, __FILE__, __LINE__);
37                 return false;
38         }
39
40         return true;
41 }
42
43 bool Monitor::add(const int fd) {
44         struct epoll_event event;
45         memset(&event, 0, sizeof(event));
46         event.data.fd = fd;
47         event.events = EPOLLIN;
48         if (epoll_ctl(mFd, EPOLL_CTL_ADD, fd, &event) != 0) {
49                 logg->logMessage("%s(%s:%i): epoll_ctl failed", __FUNCTION__, __FILE__, __LINE__);
50                 return false;
51         }
52
53         return true;
54 }
55
56 int Monitor::wait(struct epoll_event *const events, int maxevents, int timeout) {
57         int result = epoll_wait(mFd, events, maxevents, timeout);
58         if (result < 0) {
59                 // Ignore if the call was interrupted as this will happen when SIGINT is received
60                 if (errno == EINTR) {
61                         result = 0;
62                 } else {
63                         logg->logMessage("%s(%s:%i): epoll_wait failed", __FUNCTION__, __FILE__, __LINE__);
64                 }
65         }
66
67         return result;
68 }