~sircmpwn/ctools

ref: bb5007143abfc22d947c422bfade941e2a741c8c ctools/src/uname.c -rw-r--r-- 1.5 KiB
bb500714Drew DeVault link: add conformance test 2 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include <stdbool.h>
#include <stdio.h>
#include <sys/utsname.h>
#include <unistd.h>

static void
usage(void)
{
	fprintf(stderr, "usage: uname [-amnrsv]\n");
}

enum uname_fields {
	FIELD_SYSNAME = 1 << 0,
	FIELD_NODENAME = 1 << 1,
	FIELD_RELEASE = 1 << 2,
	FIELD_VERSION = 1 << 3,
	FIELD_MACHINE = 1 << 4,
	FIELD_ALL = FIELD_SYSNAME
		| FIELD_NODENAME
		| FIELD_RELEASE
		| FIELD_VERSION
		| FIELD_MACHINE,
};

static void
print_field(const char *str, bool selected)
{
	static bool first = true;

	if (!selected) {
		return;
	}

	if (!first) {
		printf(" ");
	}

	printf("%s", str);

	first = false;
}

int
main(int argc, char *argv[])
{
	enum uname_fields fields = 0;

	char opt;
	while ((opt = getopt(argc, argv, "amnrsv")) != -1) {
		switch (opt) {
		case 'a':
			fields = FIELD_ALL;
			break;
		case 'm':
			fields |= FIELD_MACHINE;
			break;
		case 'n':
			fields |= FIELD_NODENAME;
			break;
		case 'r':
			fields |= FIELD_RELEASE;
			break;
		case 's':
			fields |= FIELD_SYSNAME;
			break;
		case 'v':
			fields |= FIELD_VERSION;
			break;
		default:
			usage();
			return 1;
		}
	}

	if (fields == 0) {
		fields = FIELD_SYSNAME;
	}

	struct utsname name;
	if (uname(&name) != 0) {
		perror("uname");
		return 1;
	}

	print_field(name.sysname, fields & FIELD_SYSNAME);
	print_field(name.nodename, fields & FIELD_NODENAME);
	print_field(name.release, fields & FIELD_RELEASE);
	print_field(name.version, fields & FIELD_VERSION);
	print_field(name.machine, fields & FIELD_MACHINE);
	printf("\n");

	return 0;
}