From 3a0bb8c06789288c7152e439b4eed0007a234134 Mon Sep 17 00:00:00 2001
From: hantwofish <hankangkang5@huawei.com>
Date: Wed, 1 Nov 2023 20:18:07 +0800
Subject: [PATCH] when timeout occurs,process exits.

---
 src/common/gazelle_dfx_msg.c | 37 +++++++++++++++++++++++-------------
 src/common/gazelle_dfx_msg.h |  2 +-
 2 files changed, 25 insertions(+), 14 deletions(-)

diff --git a/src/common/gazelle_dfx_msg.c b/src/common/gazelle_dfx_msg.c
index 2070d5f..b8472be 100644
--- a/src/common/gazelle_dfx_msg.c
+++ b/src/common/gazelle_dfx_msg.c
@@ -14,28 +14,39 @@
 #include <stdio.h>
 #include <unistd.h>
 #include <errno.h>
+#include <sys/types.h>
+#include <sys/poll.h>
 
 #include "gazelle_dfx_msg.h"
 
 int read_specied_len(int fd, char *buf, size_t target_size)
 {
-    ssize_t tmp_size;
-    char *tmp_pbuf = buf;
-    while (target_size > 0) {
-        tmp_size = read(fd, tmp_pbuf, target_size);
-        if ((tmp_size == -1) && (errno != EINTR)) {
-            printf("read msg from fd %d failed, errno %d\n", fd, errno);
+    size_t total_read = 0;
+    struct pollfd fds[1];
+    fds[0].fd = fd;
+    fds[0].events = POLLIN;
+
+    while (total_read < target_size) {
+        int ret = poll(fds, 1, GAZELLECTL_TIMEOUT);
+        if (ret < 0) {
+            printf("read_specied_len:: poll ret=%d \n", ret);
             return -1;
-        } else if (tmp_size == 0) {
-            printf("read zero bytes from fd %d, maybe peer is down\n", fd);
+        } else if (ret == 0) {
+            printf("read_specied_len:: time out");
             return -1;
         }
-
-        tmp_size = (tmp_size < 0) ? 0 : tmp_size;
-        target_size -= (size_t)tmp_size;
-        tmp_pbuf += tmp_size;
+        if (fds[0].revents & POLLIN) {
+            int n = read(fd, buf + total_read, target_size - total_read);
+            if (n < 0) {
+                printf("read_specied_len:: read ret=%d", ret);
+                return -1;
+            } else if (n == 0) {
+                printf("read_specied_len:: Connection closed");
+                return -1;
+            }
+            total_read += n;
+        }
     }
-
     return 0;
 }
 
diff --git a/src/common/gazelle_dfx_msg.h b/src/common/gazelle_dfx_msg.h
index 19dddd8..93fe3df 100644
--- a/src/common/gazelle_dfx_msg.h
+++ b/src/common/gazelle_dfx_msg.h
@@ -18,7 +18,7 @@
 
 #define GAZELLE_CLIENT_NUM_MIN           1
 #define GAZELLE_LOG_LEVEL_MAX            10
-
+#define GAZELLECTL_TIMEOUT               5000 // millisecond
 /* maybe it should be consistent with MEMP_NUM_TCP_PCB */
 #define GAZELLE_LSTACK_MAX_CONN          (20000 + 2000) // same as MAX_CLIENTS + RESERVED_CLIENTS in lwipopts.h
 
-- 
2.27.0

