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.
This commit is contained in:
Paul Eggert committed 2022-01-31 12:07:39 -08:00
1 parent dba02d1996
commit aafa9bf069
1 file changed
+19 -22
+19 -22
View File
@@ -32,18 +32,22 @@
#define AUTHORS proper_name ("Jim Meyering")
#if !defined HAVE_SETHOSTNAME && defined HAVE_SYSINFO && \
defined HAVE_SYS_SYSTEMINFO_H
# include <sys/systeminfo.h>
#ifndef HAVE_SETHOSTNAME
# if defined HAVE_SYSINFO && defined HAVE_SYS_SYSTEMINFO_H
# include <sys/systeminfo.h>
# 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);
}