[LTP] [PATCH v1] libswap.c: Improve caculate swap dev number

Wei Gao wegao@suse.com
Fri Mar 1 07:27:16 CET 2024


I encounter a dead loop on following code in our test on ppc64 machine:
while ((c = fgetc(fp)) != EOF)

I think "/proc/swaps" is not normal file and can not get EOF in some situation,
so i use fgets a line and caculate swap dev number.

Signed-off-by: Wei Gao <wegao@suse.com>
---
 libs/libltpswap/libswap.c | 10 ++++++----
 1 file changed, 6 insertions(+), 4 deletions(-)

diff --git a/libs/libltpswap/libswap.c b/libs/libltpswap/libswap.c
index c8cbb8ea1..6924066b7 100644
--- a/libs/libltpswap/libswap.c
+++ b/libs/libltpswap/libswap.c
@@ -13,6 +13,7 @@
 
 #define TST_NO_DEFAULT_MAIN
 #define DEFAULT_MAX_SWAPFILE 32
+#define MAX_LINE_LEN 256
 
 #include "tst_test.h"
 #include "libswap.h"
@@ -274,16 +275,17 @@ int tst_max_swapfiles(void)
 int tst_count_swaps(void)
 {
 	FILE *fp;
-	int used = -1;
-	char c;
+	int used = 0;
 
 	fp = SAFE_FOPEN("/proc/swaps", "r");
 	if (fp == NULL)
 		return -1;
 
-	while ((c = fgetc(fp)) != EOF) {
-		if (c == '\n')
+	char line[MAX_LINE_LEN];
+	while (fgets(line, MAX_LINE_LEN, fp) != NULL) {
+		if (strstr(line, "/dev/") != NULL) {
 			used++;
+		}
 	}
 
 	SAFE_FCLOSE(fp);
-- 
2.35.3



More information about the ltp mailing list