Skip site navigation (1)Skip section navigation (2)
Date:      Sat, 14 Mar 2015 19:45:25 -0700
From:      Ivan Krivonos <int0dster@gmail.com>
To:        freebsd-hackers@freebsd.org
Subject:   ngets() consuming 100% CPU
Message-ID:  <CAF10W3zSZaH8sttrS8L3gHRNOkJEiNY1HmKXnfNmgK4TSSH56A@mail.gmail.com>

next in thread | raw e-mail | index | archive | help
Hi All,

I`ve noted that ngets() from libstand starts consuming CPU like mad when
 EOF appears on stdin. Not sure if this actually is a bug, but issue
appears
from time to time with bhyveload. Here is simpliest program allowing
 reproduce

cat > ./bget.c


#include <stdint.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/file.h>

int main()
{
        char str[512];

        for (;;) {
                ngets(str, sizeof(str));
                if (str[0] == '\n')
                        break;
        }
        return 0;
}

$ echo "balbalbalabl" | ./bget &
$

You will see bget consuming CPU in ngets() reading EOF. The patch below
fixes the problem

diff --git a/lib/libstand/gets.c b/lib/libstand/gets.c
index 7d54b00..806091a 100644
--- a/lib/libstand/gets.c
+++ b/lib/libstand/gets.c
@@ -44,8 +44,12 @@ ngets(char *buf, int n)
     int c;
     char *lp;

-    for (lp = buf;;)
-       switch (c = getchar() & 0177) {
+    for (lp = buf;;) {
+       c = getchar();
+       if (c == EOF)
+               break;
+
+       switch (c & 0177) {
        case '\n':
        case '\r':
            *lp = '\0';
@@ -79,6 +83,7 @@ ngets(char *buf, int n)
                putchar(c);
            }
        }
+    }
     /*NOTREACHED*/
 }



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?CAF10W3zSZaH8sttrS8L3gHRNOkJEiNY1HmKXnfNmgK4TSSH56A>