From cfb2d37eb6044d8b9019202be26f7d19f352e8bb Mon Sep 17 00:00:00 2001 From: Junghoon Park Date: Thu, 28 Jun 2018 14:20:43 +0900 Subject: [PATCH] Sleep and retry to write - If EAGAIN or EWOULDBLOCK happen, sleep some time and retry to write Change-Id: I40e57426d6d961b0b583cfd06388b8f6afcf1295 Signed-off-by: Junghoon Park --- src/port-internal.cc | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/src/port-internal.cc b/src/port-internal.cc index 52e9128..4287675 100644 --- a/src/port-internal.cc +++ b/src/port-internal.cc @@ -35,8 +35,10 @@ #define LOG_TAG "RPC_PORT" -#define MAX_RETRY_CNT 18 +#define MAX_RETRY_CNT 100 #define SEND_TIMEOUT 500 +#define MAX_SLEEP 100 * 1000 * 1000 +#define MIN_SLEEP 5 * 1000 * 1000 namespace rpc_port { namespace internal { @@ -61,7 +63,7 @@ int Port::Read(void* buf, unsigned int size) { unsigned int left = size; ssize_t nb; int retry_cnt = 0; - struct timespec TRY_SLEEP_TIME = { 0, 5 * 1000 * 1000 }; + struct timespec TRY_SLEEP_TIME = { 0, MIN_SLEEP }; int bytes_read = 0; char* buffer = static_cast(buf); std::lock_guard lock(mutex_); @@ -77,18 +79,20 @@ int Port::Read(void* buf, unsigned int size) { retry_cnt++; nanosleep(&TRY_SLEEP_TIME, 0); TRY_SLEEP_TIME.tv_nsec *= 2; - if (TRY_SLEEP_TIME.tv_nsec > 999999999) - TRY_SLEEP_TIME.tv_nsec = 999999999; + if (TRY_SLEEP_TIME.tv_nsec > MAX_SLEEP) + TRY_SLEEP_TIME.tv_nsec = MAX_SLEEP; continue; } + LOGE("read_socket: ...error fd %d: errno %d\n", fd_, errno); - return RPC_PORT_ERROR_IO_ERROR; + return RPC_PORT_ERROR_IO_ERROR; } left -= nb; buffer += nb; bytes_read += nb; retry_cnt = 0; + TRY_SLEEP_TIME.tv_nsec = MIN_SLEEP; } if (left != 0) { @@ -103,6 +107,7 @@ int Port::Write(const void* buf, unsigned int size) { unsigned int left = size; ssize_t nb; int retry_cnt = 0; + struct timespec TRY_SLEEP_TIME = { 0, MIN_SLEEP }; struct pollfd fds[1]; int ret; int bytes_write = 0; @@ -122,9 +127,13 @@ int Port::Write(const void* buf, unsigned int size) { while (left && (retry_cnt < MAX_RETRY_CNT)) { nb = write(fd_, buffer, left); if (nb == -1) { - if (errno == EINTR) { - LOGE("write_socket: EINTR error continue ..."); + if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK) { + LOGE("write_socket: %d errno, sleep and retry ...", errno); retry_cnt++; + nanosleep(&TRY_SLEEP_TIME, 0); + TRY_SLEEP_TIME.tv_nsec *= 2; + if (TRY_SLEEP_TIME.tv_nsec > MAX_SLEEP) + TRY_SLEEP_TIME.tv_nsec = MAX_SLEEP; continue; } @@ -136,6 +145,7 @@ int Port::Write(const void* buf, unsigned int size) { buffer += nb; bytes_write += nb; retry_cnt = 0; + TRY_SLEEP_TIME.tv_nsec = MIN_SLEEP; } if (left != 0) { -- 2.7.4