-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathhandler.cc
100 lines (77 loc) · 1.47 KB
/
handler.cc
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
#include <mp/wavy.h>
#include <mp/signal.h>
#include <mp/functional.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
#include <iostream>
using namespace mp::placeholders;
class handler : public mp::wavy::handler {
public:
handler(int fd, mp::wavy::loop* lo) :
mp::wavy::handler(fd),
m_lo(lo),
m_count(0) { }
void on_read(mp::wavy::event& e)
{
char buf[512];
ssize_t rl = read(fd(), buf, sizeof(buf));
if(rl <= 0) {
if(rl == 0) {
throw mp::system_error(errno, "connection closed");
}
if(errno == EINTR || errno == EAGAIN) { return; }
}
std::cout << "read "<<rl<<" bytes: ";
std::cout.write(buf, rl);
std::cout << std::endl;
m_lo->end();
}
private:
mp::wavy::loop* m_lo;
int m_count;
};
bool timer_handler(int* count, mp::wavy::loop* lo)
{
std::cout << "timer" << std::endl;
if(++(*count) >= 3) {
lo->end();
return false;
}
return true;
}
void my_function()
{
std::cout << "ok" << std::endl;
}
void reader_main(int rpipe)
{
mp::wavy::loop lo;
lo.add_handler<handler>(rpipe, &lo);
int count = 0;
lo.add_timer(0.1, 0.1, mp::bind(
&timer_handler, &count, &lo));
lo.submit(&my_function);
lo.run(4);
}
void writer_main(int wpipe)
{
mp::wavy::loop lo;
for(int i=0; i < 15; ++i) {
lo.write(wpipe, "test", 4);
}
lo.flush();
}
int main(void)
{
int pair[2];
pipe(pair);
pid_t pid = fork();
if(pid == 0) {
reader_main(pair[0]);
exit(0);
}
writer_main(pair[1]);
wait(NULL);
}