File: host_memory_info.c

package info (click to toggle)
cctools 9.9-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 44,624 kB
  • sloc: ansic: 192,539; python: 20,827; cpp: 20,199; sh: 11,719; perl: 4,106; xml: 3,688; makefile: 1,224
file content (84 lines) | stat: -rw-r--r-- 1,733 bytes parent folder | download | duplicates (2)
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
/*
Copyright (C) 2008- The University of Notre Dame
This software is distributed under the GNU General Public License.
See the file COPYING for details.
*/

#include "host_memory_info.h"

#if defined(CCTOOLS_OPSYS_LINUX)

#include <unistd.h>

int host_memory_info_get(UINT64_T * avail, UINT64_T * total)
{
	*total = getpagesize() * (UINT64_T) sysconf(_SC_PHYS_PAGES);
	*avail = getpagesize() * (UINT64_T) sysconf(_SC_AVPHYS_PAGES);
	return 1;
}

#elif defined(CCTOOLS_OPSYS_DARWIN)

#include <sys/types.h>
#include <sys/sysctl.h>

int host_memory_info_get(UINT64_T * avail, UINT64_T * total)
{
	unsigned x = 0;
	size_t s = sizeof(x);
	sysctlbyname("hw.physmem", &x, &s, 0, 0);
	*avail = *total = x;
	return 1;
}

#else

int host_memory_info_get(UINT64_T * avail, UINT64_T * total)
{
	*total = 0;
	*avail = 0;
	return 1;
}

#endif

#include <sys/resource.h>
#include <stdio.h>
#include <unistd.h>

int host_memory_usage_get(UINT64_T * rssp, UINT64_T * totalp)
{
#ifdef CCTOOLS_OPSYS_LINUX
	/*
	   Linux has getrusage, but it doesn't remote memory status,
	   so we must load it from the proc filesystem instead.
	 */

	unsigned long total, rss, shared, text, libs, data, dirty;

	FILE *file = fopen("/proc/self/statm", "r");
	if(!file)
		return 0;

	fscanf(file, "%lu %lu %lu %lu %lu %lu %lu", &total, &rss, &shared, &text, &libs, &data, &dirty);

	fclose(file);

	*rssp = (UINT64_T) rss *getpagesize();
	*totalp = (UINT64_T) total *getpagesize();

	return 1;
#else
	struct rusage ru;
	int result = getrusage(RUSAGE_SELF, &ru);
	if(result >= 0) {
		*rssp = (UINT64_T) ru.ru_ixrss * getpagesize();
		*totalp = (UINT64_T) ru.ru_ixrss * getpagesize();
		return 1;
	} else {
		return 0;
	}
#endif
}

/* vim: set noexpandtab tabstop=4: */