From 844c3e5e97a79da38c0a4b69610ad425774d7c30 Mon Sep 17 00:00:00 2001 From: Paul Eggert Date: Mon, 31 Jan 2022 08:42:07 -0800 Subject: [PATCH 32/43] hostname: simplify * src/hostname.c (sethostname): Provide a substitute on all platforms, to simplify the mainline code. (main): Simplify. Remove an IF_LINT. Use main_exit rather than return. --- src/hostname.c | 41 +++++++++++++++++++---------------------- 1 file changed, 19 insertions(+), 22 deletions(-) diff --git a/src/hostname.c b/src/hostname.c index 69e38bb37..e07e98b2b 100644 --- a/src/hostname.c +++ b/src/hostname.c @@ -32,18 +32,22 @@ #define AUTHORS proper_name ("Jim Meyering") -#if !defined HAVE_SETHOSTNAME && defined HAVE_SYSINFO && \ - defined HAVE_SYS_SYSTEMINFO_H -# include +#ifndef HAVE_SETHOSTNAME +# if defined HAVE_SYSINFO && defined HAVE_SYS_SYSTEMINFO_H +# include +# endif static int -sethostname (char *name, size_t namelen) +sethostname (char const *name, size_t namelen) { +# if defined HAVE_SYSINFO && defined HAVE_SYS_SYSTEMINFO_H /* Using sysinfo() is the SVR4 mechanism to set a hostname. */ return (sysinfo (SI_SET_HOSTNAME, name, namelen) < 0 ? -1 : 0); +# else + errno = ENOTSUP; + return -1; +# endif } - -# define HAVE_SETHOSTNAME 1 /* Now we have it... */ #endif void @@ -84,34 +88,27 @@ main (int argc, char **argv) Version, true, usage, AUTHORS, (char const *) NULL); - if (argc == optind + 1) + if (optind + 1 < argc) + { + error (0, 0, _("extra operand %s"), quote (argv[optind + 1])); + usage (EXIT_FAILURE); + } + + if (optind + 1 == argc) { -#ifdef HAVE_SETHOSTNAME /* Set hostname to operand. */ char const *name = argv[optind]; if (sethostname (name, strlen (name)) != 0) die (EXIT_FAILURE, errno, _("cannot set name to %s"), quote (name)); -#else - die (EXIT_FAILURE, 0, - _("cannot set hostname; this system lacks the functionality")); -#endif } - - if (argc <= optind) + else { hostname = xgethostname (); if (hostname == NULL) die (EXIT_FAILURE, errno, _("cannot determine hostname")); puts (hostname); - IF_LINT (free (hostname)); - } - - if (optind + 1 < argc) - { - error (0, 0, _("extra operand %s"), quote (argv[optind + 1])); - usage (EXIT_FAILURE); } - return EXIT_SUCCESS; + main_exit (EXIT_SUCCESS); } -- 2.32.0