diff options
author | Tom Smeding <tom.smeding@gmail.com> | 2018-08-02 18:19:21 +0200 |
---|---|---|
committer | Tom Smeding <tom.smeding@gmail.com> | 2018-08-02 18:21:15 +0200 |
commit | 134bec17a10030fc7d1b2060b57bf19799f6c780 (patch) | |
tree | 287deb14de65bd1676e04aa6bd40b72ef785c6af /serverd.c | |
parent | 8ff7ed58020b46d0bcb3b6dcbc0c5b02e85275a8 (diff) |
Proper event-driven icmpd recv
Diffstat (limited to 'serverd.c')
-rw-r--r-- | serverd.c | 62 |
1 files changed, 36 insertions, 26 deletions
@@ -15,10 +15,42 @@ int main(void) { struct icmpd *server = icmpd_create_server(-1, 0); struct icmpd *conn = NULL; + int server_fd = icmpd_get_select_fd(server); + int conn_fd = -1; + while (true) { - // printf("Iter\n"); + fd_set inset; + FD_ZERO(&inset); + FD_SET(0, &inset); + FD_SET(server_fd, &inset); + if (conn) FD_SET(conn_fd, &inset); + int nfds = maxi(0, maxi(server_fd, conn_fd)) + 1; + + int ret = select(nfds, &inset, NULL, NULL, NULL); + if (ret < 0) { + if (errno == EINTR) continue; + perror("select"); + return 1; + } + + if (ret == 0) continue; // timeout + + if (FD_ISSET(0, &inset)) { + char *line = NULL; + size_t linelen = 0; + errno = 0; + ssize_t nr = getline(&line, &linelen, stdin); + if (nr < 0) { + if (errno == 0) break; // EOF + perror("getline"); + exit(1); + } + if (nr > 0) nr--; + icmpd_send(conn, line, nr); + free(line); + } - if (icmpd_peek(server)) { + if (FD_ISSET(server_fd, &inset) && icmpd_peek(server)) { struct icmpd_received msg = icmpd_recv(server); printf("Server recv: %zu\n", msg.length); xxd(msg.data, msg.length); @@ -32,6 +64,7 @@ int main(void) { } else { conn = icmpd_create_server(msg.id, msg.source_addr); icmpd_server_set_outstanding(conn, msg.seqnum); + conn_fd = icmpd_get_select_fd(conn); // icmpd_send(conn, "dankje", 6); // icmpd_destroy(conn); @@ -40,34 +73,11 @@ int main(void) { free(msg.data); } - if (icmpd_peek(conn)) { + if (conn && FD_ISSET(conn_fd, &inset) && icmpd_peek(conn)) { struct icmpd_received msg = icmpd_recv(conn); printf("Connection recv: %zu\n", msg.length); xxd(msg.data, msg.length); free(msg.data); } - - fd_set inset; - FD_ZERO(&inset); - FD_SET(0, &inset); - struct timeval tv; - tv.tv_sec = 1; - tv.tv_usec = 0; - int ret = select(1, &inset, NULL, NULL, &tv); - if (ret < 0) { - if (errno == EINTR) continue; - perror("select"); - return 1; - } - if (ret == 0) continue; // timeout - if (FD_ISSET(0, &inset)) { - char *line = NULL; - size_t linelen = 0; - ssize_t nr = getline(&line, &linelen, stdin); - assert(nr >= 0); - if (nr > 0) nr--; - icmpd_send(conn, line, nr); - free(line); - } } } |