Shell: Clean exit on ^D and use getchar()

Use getchar() instead of fread(&ch, 1, sizeof(char), stdin). This
is much cleaner.
This commit is contained in:
Bananymous 2023-09-07 15:51:05 +03:00
parent 14ac1c9904
commit afe95be42f
1 changed files with 15 additions and 7 deletions

View File

@ -23,6 +23,12 @@ static int last_return = 0;
static BAN::String hostname; static BAN::String hostname;
static void clean_exit()
{
tcsetattr(0, TCSANOW, &old_termios);
exit(0);
}
BAN::Vector<BAN::Vector<BAN::String>> parse_command(BAN::StringView); BAN::Vector<BAN::Vector<BAN::String>> parse_command(BAN::StringView);
BAN::Optional<BAN::String> parse_dollar(BAN::StringView command, size_t& i) BAN::Optional<BAN::String> parse_dollar(BAN::StringView command, size_t& i)
@ -268,7 +274,7 @@ BAN::Optional<int> execute_builtin(BAN::Vector<BAN::String>& args, int fd_in, in
} }
else if (args.front() == "exit"sv) else if (args.front() == "exit"sv)
{ {
exit(0); clean_exit();
} }
else if (args.front() == "export"sv) else if (args.front() == "export"sv)
{ {
@ -749,8 +755,7 @@ int main(int argc, char** argv)
while (true) while (true)
{ {
uint8_t ch; uint8_t ch = getchar();
fread(&ch, 1, sizeof(char), stdin);
if (waiting_utf8 > 0) if (waiting_utf8 > 0)
{ {
@ -786,10 +791,10 @@ int main(int argc, char** argv)
switch (ch) switch (ch)
{ {
case '\e': case '\e':
fread(&ch, 1, sizeof(char), stdin); ch = getchar();
if (ch != '[') if (ch != '[')
break; break;
fread(&ch, 1, sizeof(char), stdin); ch = getchar();
switch (ch) switch (ch)
{ {
case 'A': if (index > 0) { index--; col = buffers[index].size(); fprintf(stdout, "\e[%dG%s\e[K", prompt_length() + 1, buffers[index].data()); fflush(stdout); } break; case 'A': if (index > 0) { index--; col = buffers[index].size(); fprintf(stdout, "\e[%dG%s\e[K", prompt_length() + 1, buffers[index].data()); fflush(stdout); } break;
@ -828,6 +833,10 @@ int main(int argc, char** argv)
buffers[index].clear(); buffers[index].clear();
col = 0; col = 0;
break; break;
case '\x04':
fprintf(stdout, "\n");
clean_exit();
break;
case '\n': case '\n':
fputc('\n', stdout); fputc('\n', stdout);
if (!buffers[index].empty()) if (!buffers[index].empty())
@ -852,6 +861,5 @@ int main(int argc, char** argv)
} }
} }
tcsetattr(0, TCSANOW, &old_termios); clean_exit();
return 0;
} }