Commit eeb7695e2e1cc5f5b3b1054fe5297f1e6daccae2
1 parent
0354f793
Using recv with nonblocking flag
Showing
1 changed file
with
3 additions
and
19 deletions
epoll4.c
| ... | ... | @@ -62,20 +62,6 @@ static void set_sockaddr(struct sockaddr_in *addr) { |
| 62 | 62 | addr->sin_port = htons(DEFAULT_PORT); |
| 63 | 63 | } |
| 64 | 64 | |
| 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 | - | |
| 72 | - if (fcntl(sockfd, F_SETFL, fcntl(sockfd, F_GETFL, 0) | O_NONBLOCK) == -1) { | |
| 73 | - perror("fcntl"); | |
| 74 | - exit(1); | |
| 75 | - } | |
| 76 | - return 0; | |
| 77 | -} | |
| 78 | - | |
| 79 | 65 | /* |
| 80 | 66 | * epoll echo server |
| 81 | 67 | */ |
| ... | ... | @@ -113,7 +99,6 @@ void server_run() { |
| 113 | 99 | exit(1); |
| 114 | 100 | } |
| 115 | 101 | |
| 116 | - setnonblocking(listen_sock); | |
| 117 | 102 | if (listen(listen_sock, MAX_CONN) < 0) { |
| 118 | 103 | perror("listen"); |
| 119 | 104 | exit(1); |
| ... | ... | @@ -145,13 +130,12 @@ void server_run() { |
| 145 | 130 | inet_ntop(AF_INET, (char *)&(cli_addr.sin_addr), buf, sizeof(buf)); |
| 146 | 131 | printf("[+] connected with %s:%d\n", buf, ntohs(cli_addr.sin_port)); |
| 147 | 132 | |
| 148 | - setnonblocking(conn_sock); | |
| 149 | 133 | epoll_ctl_add(epfd, conn_sock, |
| 150 | 134 | EPOLLIN | EPOLLET | EPOLLRDHUP | EPOLLHUP); |
| 151 | 135 | } else if (events[i].events & EPOLLIN) { |
| 152 | 136 | /* handle EPOLLIN event */ |
| 153 | 137 | for (;;) { |
| 154 | - n = read(events[i].data.fd, buf, sizeof(buf) - 1); | |
| 138 | + n = recv(events[i].data.fd, buf, sizeof(buf) - 1, MSG_DONTWAIT); | |
| 155 | 139 | if (n == -1 && ((errno == EAGAIN) || (errno == EWOULDBLOCK))) { |
| 156 | 140 | break; |
| 157 | 141 | } else if (n == 0) { |
| ... | ... | @@ -163,8 +147,8 @@ void server_run() { |
| 163 | 147 | while (n != strlen(buf)) { |
| 164 | 148 | int rv = send(events[i].data.fd, buf + n, strlen(buf) - n, |
| 165 | 149 | MSG_NOSIGNAL); |
| 166 | - if (rv == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) | |
| 167 | - continue; // FIXME: busy waiting - should wait using epoll | |
| 150 | + if (rv == -1 && (errno == EINTR)) | |
| 151 | + continue; // FIXME: might lock up due to client not receiving - should wait using epoll | |
| 168 | 152 | if (rv == -1) |
| 169 | 153 | break; |
| 170 | 154 | n += rv; | ... | ... |