ngets() consuming 100% CPU

Ivan Krivonos int0dster at gmail.com
Sun Mar 15 02:45:26 UTC 2015


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*/
 }


More information about the freebsd-hackers mailing list