file in core(fincore) in c
Noticed it when I was looking into PostgreSQL buffering

Fincore is David Plonka's work, available at


http://net.doit.wisc.edu/~plonka/fincore/

It's a utility tells you how much a file cached in the kernel's buffer. It is a C code, but implemented in perl INLINE module.

Here is a my pure c code, will do more later

#include <errno.h> /* errno */
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/mman.h>

int main(int argc, char *argv[]) {
int fd,cnt;
struct stat file_stat;
void *file_mmap;
unsigned char *mincore_vec;
size_t page_size = getpagesize();
size_t page_index;

fd = open(argv[1],0);
if (0 > fd) {
perror("open file error");
return 1;
}
if ( 0 != fstat(fd, &file_stat)) {
perror("fstat error ");
close(fd);
return 1;
}
file_mmap = mmap((void *)0, file_stat.st_size, PROT_NONE, MAP_SHARED, fd, 0);
if (MAP_FAILED == file_mmap) {
perror("mmap error ");
close(fd);
return 1;
}
mincore_vec = calloc(1, (file_stat.st_size+page_size-1)/page_size);
if ((void *)0 == mincore_vec) {
perror("mincore calloc error");
close(fd);
return 1;
}
if(0 == mincore(file_mmap, file_stat.st_size, mincore_vec)) {
printf("Cached Blocks of %s: ",argv[1]);
for (page_index = 0; page_index <= file_stat.st_size/page_size; page_index++) {
if (mincore_vec[page_index]&1) {
/** printf("%lu ", (unsigned long)page_index);**/
cnt++;
}
}
printf("\n total pages in core: %d\n",cnt);
free(mincore_vec);
munmap(file_mmap, file_stat.st_size);
close(fd);
return 0;
}
else{
fprintf(stderr, "mincore(%p, %lu, %p): %s\n", file_mmap, (unsigned long)file_stat.st_size, mincore_vec, strerror(errno));
free(mincore_vec);
munmap(file_mmap, file_stat.st_size);
close(fd);
return 1;
}
}

 

 

 

 

 

 

 

Comments powered by CComment