xref: /haiku/src/bin/vmstat.cpp (revision 3dfd9cb95ce45f59160d50975210bc55e3fc0709)
1 /*
2  * Copyright 2008, Axel Dörfler, axeld@pinc-software.de.
3  * Distributed under the terms of the MIT License.
4  */
5 
6 
7 #include <getopt.h>
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <string.h>
11 
12 #include <system_info.h>
13 
14 
15 static struct option const kLongOptions[] = {
16 	{"periodic", no_argument, 0, 'p'},
17 	{"rate", required_argument, 0, 'r'},
18 	{"help", no_argument, 0, 'h'},
19 	{NULL}
20 };
21 
22 extern const char *__progname;
23 static const char *kProgramName = __progname;
24 
25 
26 void
27 usage(int status)
28 {
29 	fprintf(stderr, "usage: %s [-p] [-r <time>]\n"
30 		" -p,--periodic\tDumps changes periodically every second.\n"
31 		" -r,--rate\tDumps changes periodically every <time> milli seconds.\n",
32 		kProgramName);
33 
34 	exit(status);
35 }
36 
37 
38 int
39 main(int argc, char** argv)
40 {
41 	bool periodically = false;
42 	bigtime_t rate = 1000000LL;
43 
44 	int c;
45 	while ((c = getopt_long(argc, argv, "pr:h", kLongOptions, NULL)) != -1) {
46 		switch (c) {
47 			case 0:
48 				break;
49 			case 'p':
50 				periodically = true;
51 				break;
52 			case 'r':
53 				rate = atoi(optarg) * 1000LL;
54 				if (rate <= 0) {
55 					fprintf(stderr, "%s: Invalid rate: %s\n",
56 						kProgramName, optarg);
57 					return 1;
58 				}
59 				periodically = true;
60 				break;
61 			case 'h':
62 				usage(0);
63 				break;
64 			default:
65 				usage(1);
66 				break;
67 		}
68 	}
69 	system_memory_info info;
70 	status_t status = __get_system_info_etc(B_MEMORY_INFO, &info,
71 		sizeof(system_memory_info));
72 	if (status != B_OK) {
73 		fprintf(stderr, "%s: cannot get system info: %s\n", kProgramName,
74 			strerror(status));
75 		return 1;
76 	}
77 
78 	printf("max memory:\t\t%Lu\n", info.max_memory);
79 	printf("free memory:\t\t%Lu\n", info.free_memory);
80 	printf("needed memory:\t\t%Lu\n", info.needed_memory);
81 	printf("block cache memory:\t%Lu\n", info.block_cache_memory);
82 	printf("max swap space:\t\t%Lu\n", info.max_swap_space);
83 	printf("free swap space:\t%Lu\n", info.free_swap_space);
84 	printf("page faults:\t\t%lu\n", info.page_faults);
85 
86 	if (periodically) {
87 		puts("\npage faults  used memory    used swap  block cache");
88 		system_memory_info lastInfo = info;
89 
90 		while (true) {
91 			snooze(rate);
92 
93 			__get_system_info_etc(B_MEMORY_INFO, &info,
94 				sizeof(system_memory_info));
95 
96 			printf("%11ld  %11Ld  %11Ld  %11Ld\n",
97 				(int32)info.page_faults - lastInfo.page_faults,
98 				(info.max_memory - info.free_memory)
99 					- (lastInfo.max_memory - lastInfo.free_memory),
100 				(info.max_swap_space - info.free_swap_space)
101 					- (lastInfo.max_swap_space - lastInfo.free_swap_space),
102 				info.block_cache_memory - lastInfo.block_cache_memory);
103 
104 			lastInfo = info;
105 		}
106 	}
107 
108 	return 0;
109 }
110