From 20d38ed28c85c6963f00bb74266e890f72e5f29c Mon Sep 17 00:00:00 2001 From: Bananymous Date: Wed, 31 Jul 2024 23:53:55 +0300 Subject: [PATCH] LibC/Shell: Implement gethostname() and shell uses it for hostname --- userspace/libraries/LibC/unistd.cpp | 13 +++++++++++++ userspace/programs/Shell/main.cpp | 18 +++--------------- 2 files changed, 16 insertions(+), 15 deletions(-) diff --git a/userspace/libraries/LibC/unistd.cpp b/userspace/libraries/LibC/unistd.cpp index 3a68e5ed44..8a85ebab32 100644 --- a/userspace/libraries/LibC/unistd.cpp +++ b/userspace/libraries/LibC/unistd.cpp @@ -119,6 +119,19 @@ int isatty(int fildes) return syscall(SYS_ISATTY, fildes) >= 0; } +int gethostname(char* name, size_t namelen) +{ + FILE* fp = fopen("/etc/hostname", "r"); + if (fp == NULL) + return -1; + size_t nread = fread(name, namelen - 1, 1, fp); + while (nread > 0 && name[nread - 1] == '\n') + nread--; + name[nread] = '\0'; + fclose(fp); + return 0; +} + int execl(const char* pathname, const char* arg0, ...) { if (arg0 == nullptr) diff --git a/userspace/programs/Shell/main.cpp b/userspace/programs/Shell/main.cpp index 0668d7ec51..1067242d91 100644 --- a/userspace/programs/Shell/main.cpp +++ b/userspace/programs/Shell/main.cpp @@ -915,21 +915,9 @@ int main(int argc, char** argv) tcgetattr(0, &old_termios); - { - FILE* fp = fopen("/etc/hostname", "r"); - if (fp != NULL) - { - char buffer[512]; - while (size_t nbyte = fread(buffer, 1, sizeof(buffer), fp)) - { - if (nbyte == 0) - break; - MUST(hostname.append(BAN::StringView(buffer, nbyte))); - } - fclose(fp); - } - if (!hostname.empty() && hostname.back() == '\n') - hostname.pop_back(); + char hostname_buffer[HOST_NAME_MAX]; + if (gethostname(hostname_buffer, sizeof(hostname_buffer)) == 0) { + MUST(hostname.append(hostname_buffer)); } if (argc >= 2)