From 515f911ec1618d7cf28b977d28c595e43cb7d6a5 Mon Sep 17 00:00:00 2001 From: kolban Date: Mon, 19 Dec 2016 16:29:05 -0600 Subject: [PATCH] Addition of optional select() for debug transport --- AUTHORS.rst | 1 + .../duk_trans_socket_unix.c | 36 +++++++++++++++++-- 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/AUTHORS.rst b/AUTHORS.rst index a0bb74dd..23ca7ab4 100644 --- a/AUTHORS.rst +++ b/AUTHORS.rst @@ -78,6 +78,7 @@ bugs, provided ideas, etc; roughly in order of appearance): * Michael Drake (https://github.com/tlsa) * https://github.com/chris-y * Laurent Zubiaur (https://github.com/lzubiaur) +* Neil Kolban (https://github.com/nkolban) If you are accidentally missing from this list, send me an e-mail (``sami.vaarala@iki.fi``) and I'll fix the omission. diff --git a/examples/debug-trans-socket/duk_trans_socket_unix.c b/examples/debug-trans-socket/duk_trans_socket_unix.c index ac74de2b..b36ba89e 100644 --- a/examples/debug-trans-socket/duk_trans_socket_unix.c +++ b/examples/debug-trans-socket/duk_trans_socket_unix.c @@ -5,12 +5,27 @@ * After that data is just passed through. */ +/* + * The select() vs poll() story. The two system calls called + * "select()" and "poll()" are similar but not necessarily available + * on all platforms. The default implementation is to use "poll()" + * but we can switch that by defining "USE_SELECT" within this + * file. For example: + * + * #define USE_SELECT + * + * If set, instead of leveraging "poll()", this code will leverage + * "select()". Discussions on "poll()" vs "select()" can be read + * about here: https://daniel.haxx.se/docs/poll-vs-select.html + */ #include #include #include #include #include +#if !defined(USE_SELECT) #include +#endif /* ! USE_SELECT */ #include #include "duktape.h" @@ -253,8 +268,12 @@ duk_size_t duk_trans_socket_write_cb(void *udata, const char *buffer, duk_size_t } duk_size_t duk_trans_socket_peek_cb(void *udata) { +#if defined(USE_SELECT) + fd_set rfds; +#else /* USE_SELECT */ struct pollfd fds[1]; int poll_rc; +#endif /* USE_SELECT */ (void) udata; /* not needed by the example */ @@ -266,7 +285,20 @@ duk_size_t duk_trans_socket_peek_cb(void *udata) { if (client_sock < 0) { return 0; } - +#if defined(USE_SELECT) + FD_ZERO(&rfds); + FD_SET(client_sock, &rfds); + struct timeval tm; + tm.tv_sec = tm.tv_usec = 0; + int select_rc = select(client_sock + 1, &rfds, NULL, NULL, &tm); + if (select_rc == 0) { + return 0; + } + if (select_rc == 1) { + return 1; + } + goto fail; +#else /* USE_SELECT */ fds[0].fd = client_sock; fds[0].events = POLLIN; fds[0].revents = 0; @@ -287,7 +319,7 @@ duk_size_t duk_trans_socket_peek_cb(void *udata) { } else { return 1; /* something to read */ } - +#endif /* USE_SELECT */ fail: if (client_sock >= 0) { (void) close(client_sock);