-
Notifications
You must be signed in to change notification settings - Fork 0
/
Channel.cpp
129 lines (108 loc) · 2.21 KB
/
Channel.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#include"EventLoop.h"
#include"Channel.h"
#include"base/Logging.h"
#include<poll.h>
#include<assert.h>
#include<sstream>
const int Channel::kNoneEvent=0;
const int Channel::kReadEvent=POLLIN|POLLPRI;
const int Channel::kWriteEvent=POLLOUT;
Channel::Channel(EventLoop *loop,int fd)
: loop_(loop),
fd_(fd),
events_(kNoneEvent),
revents_(kNoneEvent),
index_(-1),
tie_(),
tied_(false),
eventHandling_(false),
addedToLoop_(false)
{
}
Channel::~Channel()
{
assert(!eventHandling_);
assert(!addedToLoop_);
if(loop_->isInLoopThread())
{
assert(!loop_->hasChannel(this));
}
}
void Channel::update()
{
addedToLoop_=true;
loop_->updateChannel(this);
}
void Channel::tie(const std::shared_ptr<void> &obj)
{
tied_=true;
tie_=obj;
}
void Channel::remove()
{
assert(isNoneEvent());
addedToLoop_=false;
loop_->removeChannel(this);
}
void Channel::handleEvent()
{
std::shared_ptr<void> ptr;
if(tied_)
{
ptr=tie_.lock();
if(ptr)
{
handleEventWithGuard();
}
}
else
{
handleEventWithGuard();
}
}
void Channel::handleEventWithGuard()
{
eventHandling_=true;
Log<<eventsToString(fd_,revents_);
if(revents_&POLLNVAL)
Log<<" WARNING Channel::handleEvent() POLLNVAL"<<"\n";
if(revents_&(POLLERR|POLLNVAL))
{
if(errorCallback_)
errorCallback_();
}
if ((revents_ & POLLHUP) && !(revents_ & POLLIN))
{
if(closeCallback_)
closeCallback_();
}
if(revents_&(POLLIN|POLLPRI|POLLHUP))
{ Log<<"fd: "<<fd_<<eventsToString(fd_,revents_);
if(readCallback_)
readCallback_();
}
if(revents_&(POLLOUT))
{
if(writeCallback_)
writeCallback_();
}
eventHandling_=false;
}
std::string Channel::eventsToString(int fd,int ev)
{
std::ostringstream oss;
oss<<fd<<": ";
if(ev&POLLIN)
oss<<"IN ";
if(ev&POLLPRI)
oss<<"PRI ";
if(ev&POLLOUT)
oss<<"OUT ";
if(ev&POLLHUP)
oss<<"HUP ";
if (ev & POLLERR)
oss << "ERR ";
if (ev & POLLNVAL)
oss << "NVAL ";
return oss.str();
}