FENIX_coreutils/uname.c

74 lines
1.8 KiB
C
Raw Normal View History

#define _POSIX_C_SOURCE 200809L
2020-12-11 13:19:04 +00:00
#include <stdio.h>
#include <sys/utsname.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char * argv[]) {
/* The utsname struct has to be preallocated for uname() to work. */
struct utsname * sys_name = malloc(sizeof(*sys_name));
if(sys_name == NULL) {
fprintf(stderr, "%s: insufficient memory\n", argv[0]);
return 2;
}
int stuff_printed = 0;
char c;
/*
2022-10-09 16:41:27 +00:00
This variable holds what all we need to print, corresponding
to the following options:
01: -m (Machine type)
02: -n (Hostname)
04: -r (Release)
010: -s (Operating system)
020: -v (Version)
037: -a (Everything)
2020-12-11 13:19:04 +00:00
*/
int stuff_print = 0;
2022-10-09 16:41:27 +00:00
/* Get options */
2020-12-11 13:19:04 +00:00
while((c = getopt(argc, argv, "amnrsv")) != -1) {
switch(c) {
case 'm': stuff_print |= 01; break;
case 'n': stuff_print |= 02; break;
case 'r': stuff_print |= 04; break;
case 's': stuff_print |= 010; break;
case 'v': stuff_print |= 020; break;
case 'a': stuff_print |= 037; break;
}
2022-10-09 16:41:27 +00:00
/* If we saw -a, then just leave, we're done here. */
2020-12-11 13:19:04 +00:00
if(c == 'a') { break; }
}
2022-10-09 16:41:27 +00:00
/* If no options specified, print OS name */
2020-12-11 13:19:04 +00:00
if(stuff_print == 0) {
stuff_print = 010;
}
int got_uname = 0;
2022-10-09 16:41:27 +00:00
got_uname = uname(sys_name); /* Try to get the utsname struct */
2020-12-11 13:19:04 +00:00
if(got_uname == -1) {
fprintf(stderr, "%s: could not get uname\n", argv[0]);
return 1;
}
2022-10-09 16:41:27 +00:00
/* Print everything and trailing newline */
2020-12-11 13:19:04 +00:00
if(stuff_print & 010) {
printf("%s ", sys_name->sysname);
}
if(stuff_print & 02) {
printf("%s ", sys_name->nodename);
}
if(stuff_print & 04) {
printf("%s ", sys_name->release);
}
if(stuff_print & 020) {
printf("%s ", sys_name->version);
}
if(stuff_print & 01) {
printf("%s", sys_name->machine);
}
printf("\n");
return 0;
}