From 036828ff43a91944f4de22bbb821984d36d6aff4 Mon Sep 17 00:00:00 2001 From: Andrew Kaster Date: Sat, 23 Jan 2021 21:58:14 -0700 Subject: [PATCH] Userland: Use getline instead of Core::File::standard_input in grep Core::IODevice (which Core::File inherits from) does not have a reasonable way to block for a line. grep was spinning on IODevice::read_line, passing endless empty strings to the matcher lambda. Use getline instead, which will at least block in the Kernel for characters to be available on stdin and only return full lines (or eof) --- Userland/Utilities/grep.cpp | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/Userland/Utilities/grep.cpp b/Userland/Utilities/grep.cpp index 25ab2e900c..8022fc487c 100644 --- a/Userland/Utilities/grep.cpp +++ b/Userland/Utilities/grep.cpp @@ -25,6 +25,7 @@ */ #include +#include #include #include #include @@ -186,15 +187,19 @@ int main(int argc, char** argv) }; if (!files.size() && !recursive) { - auto stdin_file = Core::File::standard_input(); - while (!stdin_file->eof()) { - auto line = stdin_file->read_line(); - bool is_binary = line.bytes().contains_slow(0); + char* line = nullptr; + size_t line_len = 0; + ssize_t nread = 0; + ScopeGuard free_line = [line] { free(line); }; + while ((nread = getline(&line, &line_len, stdin)) != -1) { + ASSERT(nread > 0); + StringView line_view(line, nread - 1); + bool is_binary = line_view.contains(0); if (is_binary && binary_mode == BinaryFileMode::Skip) return 1; - if (matches(line, "stdin", false, is_binary) && is_binary && binary_mode == BinaryFileMode::Binary) + if (matches(line_view, "stdin", false, is_binary) && is_binary && binary_mode == BinaryFileMode::Binary) return 0; } } else {