uname.c (2354B)
- // utils-std: Collection of commonly available Unix tools
- // SPDX-FileCopyrightText: 2017-2022 Haelwenn (lanodan) Monnier <contact+utils@hacktivis.me>
- // SPDX-License-Identifier: MPL-2.0
- #define _POSIX_C_SOURCE 200809L
- #include "../lib/bitmasks.h"
- #include <errno.h>
- #include <stdio.h> // printf
- #include <stdlib.h> // exit, abort
- #include <string.h> // strerror
- #include <sys/utsname.h> // uname
- #include <unistd.h> // getopt
- enum uname_names
- {
- CMD_UNAME_SYSNAME = 1 << 1,
- CMD_UNAME_NODENAME = 1 << 2,
- CMD_UNAME_RELEASE = 1 << 3,
- CMD_UNAME_VERSION = 1 << 4,
- CMD_UNAME_MACHINE = 1 << 5,
- CMD_UNAME_ALL = CMD_UNAME_SYSNAME | CMD_UNAME_NODENAME | CMD_UNAME_RELEASE | CMD_UNAME_VERSION |
- CMD_UNAME_MACHINE,
- };
- const char *fmt = "%s";
- enum uname_names names = 0;
- static void
- maybe_print_name(enum uname_names key, char *value)
- {
- if(FIELD_MATCH(names, key))
- {
- if(printf(fmt, value) < 0)
- {
- fprintf(stderr, "uname: error: Failed writing %s", strerror(errno));
- exit(1);
- }
- fmt = " %s";
- }
- }
- static void
- usage(void)
- {
- fprintf(stderr, "Usage: uname [-amnprsv]\n");
- }
- int
- main(int argc, char *argv[])
- {
- int c = -1;
- while((c = getopt(argc, argv, ":amnprsv")) != -1)
- {
- switch(c)
- {
- case 'a':
- names = CMD_UNAME_ALL;
- break;
- case 'p':
- case 'm':
- names |= CMD_UNAME_MACHINE;
- break;
- case 'n':
- names |= CMD_UNAME_NODENAME;
- break;
- case 'r':
- names |= CMD_UNAME_RELEASE;
- break;
- case 's':
- names |= CMD_UNAME_SYSNAME;
- break;
- case 'v':
- names |= CMD_UNAME_VERSION;
- break;
- case ':':
- fprintf(stderr, "uname: error: Missing operand for option: '-%c'\n", optopt);
- usage();
- return 1;
- case '?':
- fprintf(stderr, "uname: error: Unrecognised option: '-%c'\n", optopt);
- usage();
- return 1;
- default:
- abort();
- }
- }
- if(names == 0) names |= CMD_UNAME_SYSNAME;
- struct utsname name;
- if(uname(&name) != 0)
- {
- fprintf(stderr,
- "uname: error: Failed getting current system names via uname(): %s\n",
- strerror(errno));
- return 1;
- }
- maybe_print_name(CMD_UNAME_SYSNAME, name.sysname);
- maybe_print_name(CMD_UNAME_NODENAME, name.nodename);
- maybe_print_name(CMD_UNAME_RELEASE, name.release);
- maybe_print_name(CMD_UNAME_VERSION, name.version);
- maybe_print_name(CMD_UNAME_MACHINE, name.machine);
- printf("\n");
- return 0;
- }