-
Notifications
You must be signed in to change notification settings - Fork 11
/
epoll-13-socketpair.cpp
95 lines (77 loc) · 1.57 KB
/
epoll-13-socketpair.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
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/epoll.h>
#define EVENTS 8
int soc[2];
void processA(){
sleep(3);
printf("processA: send message\n");
write(soc[0], "HELLO\n", 6);
return;
}
void processB(){
int epfd;
epoll_event ev, ev_ret[EVENTS];
int nfds;
int i;
char buf[128];
epfd = epoll_create(1);
if(epfd < 0){
perror("epoll_create");
return ;
}
memset(&ev, 0, sizeof(ev));
ev.events = EPOLLIN;
ev.data.fd = soc[1];
if(epoll_ctl(epfd, EPOLL_CTL_ADD, soc[1], &ev) != 0){
perror("epoll_clt");
return ;
}
memset(&ev, 0, sizeof(ev));
ev.events = EPOLLIN;
ev.data.fd = fileno(stdin);
if(epoll_ctl(epfd, EPOLL_CTL_ADD, fileno(stdin), &ev) != 0){
perror("epoll_clt1");
return ;
}
while(1){
printf("before epoll_wait\n");
nfds = epoll_wait(epfd, ev_ret, EVENTS , -1);
if(nfds < 0){
perror("epoll_wait");
return;
}
printf("after epoll_wait\n");
for(i = 0; i < nfds; ++i){
if(ev_ret[i].data.fd == soc[1]){
printf("processB:break message from socketpair\n");
goto outofloop;
}
else if(ev_ret[i].data.fd == fileno(stdin)){
read(fileno(stdin), buf, sizeof(buf));
printf("processB:input from stdin\n");
}
}
}
outofloop:
printf("process B:outside of loop\n");
return ;
}
int main(){
int ret;
ret = socketpair(AF_UNIX, SOCK_STREAM, 0, soc);
if(ret != 0){
perror("socketpair");
return 1;
}
if(fork() == 0){
processA();
}
else{
processB();
}
return 0;
}