From 03fb60893cf59e16f26d1f6d84b8a4921bbe8eae Mon Sep 17 00:00:00 2001 From: Francis Deslauriers Date: Fri, 3 May 2019 15:11:00 -0400 Subject: [PATCH] common: add bt_common_read() function MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit This function wraps the `read()` function to handle EINTR and partial reads. It returns the `count` value on success, or a smaller value than `count` on error. Signed-off-by: Francis Deslauriers Change-Id: Ib0385855447200d97a58da704dcf68423e857033 Reviewed-on: https://review.lttng.org/c/babeltrace/+/1248 Reviewed-by: Jérémie Galarneau --- include/babeltrace/common-internal.h | 52 +++++++++++++++++++++++++++- 1 file changed, 51 insertions(+), 1 deletion(-) diff --git a/include/babeltrace/common-internal.h b/include/babeltrace/common-internal.h index 0e84e8fa..19594fe3 100644 --- a/include/babeltrace/common-internal.h +++ b/include/babeltrace/common-internal.h @@ -32,9 +32,10 @@ #include #include #include -#include #include +#include #include +#include #include #define BT_COMMON_COLOR_RESET "\033[0m" @@ -305,6 +306,55 @@ void bt_common_custom_snprintf(char *buf, size_t buf_size, BT_HIDDEN size_t bt_common_get_page_size(void); +/* + * Wraps read() function to handle EINTR and partial reads. + * On success, it returns `count` received as parameter. On error, it returns a + * value smaller than the requested `count`. + */ +static inline +ssize_t bt_common_read(int fd, void *buf, size_t count) +{ + size_t i = 0; + ssize_t ret; + + BT_ASSERT(buf); + + /* Never return an overflow value. */ + BT_ASSERT(count <= SSIZE_MAX); + + do { + ret = read(fd, buf + i, count - i); + if (ret < 0) { + if (errno == EINTR) { +#ifdef BT_LOGD_STR + BT_LOGD_STR("read() call interrupted. Retrying..."); +#endif + /* retry operation */ + continue; + } else { +#ifdef BT_LOGE_ERRNO + BT_LOGE_ERRNO("Error while reading", ": fd=%d", + fd); +#endif + goto end; + } + } + i += ret; + BT_ASSERT(i <= count); + } while (count - i > 0 && ret > 0); + +end: + if (ret >= 0) { + if (i == 0) { + ret = -1; + } else { + ret = i; + } + } + + return ret; +} + static inline const char *bt_common_field_class_type_string(enum bt_field_class_type class_type) { -- 2.34.1