From 524200171fa67f9e05f62c9b5c97740ffbd343c4 Mon Sep 17 00:00:00 2001 From: Arkadiusz Bokowy Date: Thu, 17 Feb 2022 14:29:50 +0100 Subject: [PATCH] Exit shell in case of Ctrl-D input with empty line (#15294) This commit adds a default EOT handler to the shell main loop. With that, the shell app can be exited with Ctrl+D keyboard sequence. --- src/lib/shell/MainLoopDefault.cpp | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/src/lib/shell/MainLoopDefault.cpp b/src/lib/shell/MainLoopDefault.cpp index f077a7cab3b8d6..52127ec086f6eb 100644 --- a/src/lib/shell/MainLoopDefault.cpp +++ b/src/lib/shell/MainLoopDefault.cpp @@ -31,7 +31,7 @@ using chip::Shell::streamer_get; namespace { -void ReadLine(char * buffer, size_t max) +ssize_t ReadLine(char * buffer, size_t max) { ssize_t read = 0; bool done = false; @@ -56,6 +56,15 @@ void ReadLine(char * buffer, size_t max) *inptr = 0; // null terminate done = true; break; + case 0x04: + // Delete EOT character. + inptr -= 1; + // Stop the read loop if the input is still empty. + if (inptr == buffer - 1) + { + done = true; + } + break; case 0x7F: // delete backspace character + 1 more inptr -= 2; @@ -84,6 +93,9 @@ void ReadLine(char * buffer, size_t max) read--; } } + + // Return the length of the buffer including the terminating null byte. + return inptr - buffer; } bool IsSeparator(char ch) @@ -186,7 +198,11 @@ void Engine::RunMainLoop() while (true) { char * line = static_cast(Platform::MemoryAlloc(CHIP_SHELL_MAX_LINE_SIZE)); - ReadLine(line, CHIP_SHELL_MAX_LINE_SIZE); + if (ReadLine(line, CHIP_SHELL_MAX_LINE_SIZE) == 0) + { + // Stop loop in case of empty read (Ctrl-D). + break; + } #if CONFIG_DEVICE_LAYER DeviceLayer::PlatformMgr().ScheduleWork(ProcessShellLine, reinterpret_cast(line)); #else