summaryrefslogtreecommitdiff
path: root/hardware.c
blob: de2ad6886514cdd6227b3cef63703b32c8172cb5 (plain)
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
94
95
96
97
98
99
100
101
102
103
104
105
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include <proccpuinfo.h>

#include "cleanbench.h"

#define BUF_SIZ 1024

/******************
** removeNewLine **
*******************
** Removes a trailing newline character if present
*/
static void removeNewLine(char * s) {
	int len = strlen(s);

	if(len > 0 && s[len - 1] == '\n') {
		s[len - 1] = '\0';
	}
}

/***************
** runCommand **
****************
** Run the system command through a pipe
** The pointer result must point to a pre-allocated array of at least BUF_SIZ
*/
static void runCommand (const char *command, char *result) {
	FILE * pipe;

	pipe = popen(command, "r");
	if(pipe == NULL) {
		/* command failed */
		result[0] = '\0';
	} else {
		if(NULL == fgets(result, BUF_SIZ, pipe)) {
			/* command failed */
			result[0] = '\0';
		}
		pclose(pipe);
	}

	removeNewLine(result);
}

/********************
** readProcCpuInfo **
*********************
** Reads and parses /proc/cpuinfo on a Linux system
** The pointers must point to pre-allocated arrays of at least BUF_SIZ
*/
static void readProcCpuInfo (char *model, char *cache) {
	char format[32];
	proccpuinfo *info = proccpuinfo_read();

	if (!info) {
		return;
	}

	switch (info->cpus) {
	case 1:
		strcpy(format, "%s %s %.0fMHz");
		break;
	case 2:
		strcpy(format, "Dual %s %s %.0fMHz");
		break;
	default:
		strcpy(format, "%d CPUs %s %s %.0fMHz");
		break;
	}
	snprintf(model, BUF_SIZ, format, info->hardware_platform, info->architecture, info->frequency);
	snprintf(cache, BUF_SIZ, "%u KB", info->cache);
	proccpuinfo_free(info);
}

/*************
** hardware **
**************
** Runs the system command "uname -s -r"
** Reads /proc/cpuinfo if on a linux system
** Writes output
*/

void hardware(void) {
	char os[BUF_SIZ];
	char model[BUF_SIZ];
	char cache[BUF_SIZ];
	const char os_command[] = "uname -s -r";
#ifdef NO_UNAME
	os[0] = '\0';
#else
	runCommand(os_command, os);
#endif
	if(NULL != strstr(os, "Linux")) {
		readProcCpuInfo (model, cache);
	} else {
		model[0] = '\0';
		cache[0] = '\0';
	}
	printf("CPU                 : %s\n", model);
	printf("L2 Cache            : %s\n", cache);
	printf("OS                  : %s\n", os);
}