From abe8e99ee654241c0c0d5003dc64c944c749125e Mon Sep 17 00:00:00 2001 From: Lennart Poettering Date: Wed, 17 Jul 2024 15:56:15 +0200 Subject: [PATCH] terminal-util: try to avoid reading more from terminal than we need in get_default_background_color() --- src/basic/terminal-util.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/basic/terminal-util.c b/src/basic/terminal-util.c index 058f8df1097..635b5f62ee4 100644 --- a/src/basic/terminal-util.c +++ b/src/basic/terminal-util.c @@ -1830,11 +1830,11 @@ int get_default_background_color(double *ret_red, double *ret_green, double *ret goto finish; usec_t end = usec_add(now(CLOCK_MONOTONIC), 100 * USEC_PER_MSEC); - char buf[256]; + char buf[STRLEN("\x1B]11;rgb:0/0/0\x07")]; /* shortest possible reply */ size_t buf_full = 0; BackgroundColorContext context = {}; - for (;;) { + for (bool first = true;; first = false) { if (buf_full == 0) { usec_t n = now(CLOCK_MONOTONIC); @@ -1851,7 +1851,10 @@ int get_default_background_color(double *ret_red, double *ret_green, double *ret goto finish; } - ssize_t l = read(STDIN_FILENO, buf, sizeof(buf)); + /* On the first try, read multiple characters, i.e. the shortest valid + * reply. Afterwards read byte-wise, since we don't want to read too much, and + * unnecessarily drop too many characters from the input queue. */ + ssize_t l = read(STDIN_FILENO, buf, first ? sizeof(buf) : 1); if (l < 0) { r = -errno; goto finish; -- 2.47.3