pcu.git  about / heads / tags
page cache utilities for Linux
blob 3309bd9c9c299a90c7373dbabedb57dfa310a2be 1334 bytes (raw)
$ git show v0.1.0:mincore.c	# shows this blob on the CLI

 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
 
#include "compat-util.h"

static void mincore_stats(const char *path)
{
	struct stat sb;
	char *map;
	unsigned char *vec;
	size_t vec_len;
	size_t map_len;
	int fd;
	size_t i;

	if ((fd = open(path, O_RDONLY)) < 0) {
		fprintf(stderr, "%s: open(): %s\n", path, strerror(errno));
		return;
	}

	if (fstat(fd, &sb) < 0) {
		fprintf(stderr, "%s: fstat(%d): %s\n",
		        path, fd, strerror(errno));
		goto err_close;
	}

	vec_len = (sb.st_size + page_size() - 1) / page_size();
	if (!(vec = malloc(vec_len))) {
		fprintf(stderr, "%s: malloc(%lu): %s\n",
		        path, (unsigned long)vec_len, strerror(errno));
		goto err_close;
	}

	map_len = PAGE_ALIGN(sb.st_size);
	if (!(map = mmap(NULL, map_len, PROT_READ, MAP_SHARED, fd, 0))) {
		fprintf(stderr, "%s: mmap(%lu): %s\n",
		        path, (unsigned long)vec_len, strerror(errno));
		goto err_free;
	}

	if (mincore(map, map_len, vec) < 0) {
		fprintf(stderr, "%s: mincore(%lu): %s\n",
		        path, (unsigned long)vec_len, strerror(errno));
		goto err_munmap;
	}

	for (i = 0; i < vec_len; ++i)
		printf("%s: [%08lu] %x\n",
		       path, (unsigned long)i,
		       (vec[i]));
err_munmap:
	munmap(map, map_len);
err_free:
	free(vec);
err_close:
	close(fd);
}

int main(int argc, char * const argv[])
{
	int i;

	for (i = 1; i < argc; ++i)
		mincore_stats(argv[i]);
	return 0;
}

git clone https://yhbt.net/pcu.git