Commit 0354f79351baa7a4355ba3d6141fe19d95386439
1 parent
d7575a75
Added more error handling
Showing
1 changed file
with
30 additions
and
9 deletions
epoll4.c
1 | -/* | |
2 | - * Attention: | |
3 | - * To keep things simple, do not handle | |
4 | - * socket/bind/listen/.../epoll_create/epoll_wait API error | |
5 | - */ | |
6 | 1 | #include <arpa/inet.h> |
7 | 2 | #include <errno.h> |
8 | 3 | #include <fcntl.h> |
... | ... | @@ -68,9 +63,15 @@ static void set_sockaddr(struct sockaddr_in *addr) { |
68 | 63 | } |
69 | 64 | |
70 | 65 | static int setnonblocking(int sockfd) { |
66 | + int prev = fcntl(sockfd, F_GETFL, 0); | |
67 | + if (prev == -1) { | |
68 | + perror("fcntl"); | |
69 | + exit(1); | |
70 | + } | |
71 | + | |
71 | 72 | if (fcntl(sockfd, F_SETFL, fcntl(sockfd, F_GETFL, 0) | O_NONBLOCK) == -1) { |
72 | - perror("fcntl set nonblock"); | |
73 | - return -1; | |
73 | + perror("fcntl"); | |
74 | + exit(1); | |
74 | 75 | } |
75 | 76 | return 0; |
76 | 77 | } |
... | ... | @@ -93,12 +94,19 @@ void server_run() { |
93 | 94 | |
94 | 95 | listen_sock = socket(AF_INET, SOCK_STREAM, 0); |
95 | 96 | |
97 | + if (listen_sock == -1) { | |
98 | + perror("socket"); | |
99 | + exit(1); | |
100 | + } | |
101 | + | |
96 | 102 | set_sockaddr(&srv_addr); |
97 | 103 | |
98 | 104 | int reuseaddr = 1; |
99 | 105 | if (setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, |
100 | - sizeof(int)) < 0) | |
106 | + sizeof(int)) < 0) { | |
101 | 107 | perror("setsockopt(SO_REUSEADDR)"); |
108 | + exit(1); | |
109 | + } | |
102 | 110 | |
103 | 111 | if (bind(listen_sock, (struct sockaddr *)&srv_addr, sizeof(srv_addr)) < 0) { |
104 | 112 | perror("bind"); |
... | ... | @@ -112,6 +120,11 @@ void server_run() { |
112 | 120 | } |
113 | 121 | |
114 | 122 | epfd = epoll_create(1); |
123 | + if (epfd == -1) { | |
124 | + perror("epoll_create"); | |
125 | + exit(1); | |
126 | + } | |
127 | + | |
115 | 128 | epoll_ctl_add(epfd, listen_sock, EPOLLIN | EPOLLOUT); |
116 | 129 | |
117 | 130 | socklen = sizeof(cli_addr); |
... | ... | @@ -164,7 +177,11 @@ void server_run() { |
164 | 177 | /* check if the connection is closing */ |
165 | 178 | if (events[i].events & (EPOLLRDHUP | EPOLLHUP)) { |
166 | 179 | printf("[+] connection closed\n"); |
167 | - epoll_ctl(epfd, EPOLL_CTL_DEL, events[i].data.fd, NULL); | |
180 | + | |
181 | + if (epoll_ctl(epfd, EPOLL_CTL_DEL, events[i].data.fd, NULL) == -1) { | |
182 | + perror("epoll_ctl"); | |
183 | + exit(1); | |
184 | + } | |
168 | 185 | close(events[i].data.fd); |
169 | 186 | continue; |
170 | 187 | } |
... | ... | @@ -183,6 +200,10 @@ void client_run() { |
183 | 200 | struct sockaddr_in srv_addr; |
184 | 201 | |
185 | 202 | sockfd = socket(AF_INET, SOCK_STREAM, 0); |
203 | + if (sockfd == -1) { | |
204 | + perror("socket"); | |
205 | + exit(1); | |
206 | + } | |
186 | 207 | |
187 | 208 | set_sockaddr(&srv_addr); |
188 | 209 | ... | ... |