We write a benchmark tool in C++ where we want to clear the filesystem memory cache between experiments.

bash code
sync
echo 3 > /proc/sys/vm/drop_caches

My question is how can we do this programmatically directly within C++?

Try this :

bash code
sync();

std::ofstream ofs("/proc/sys/vm/drop_caches");
ofs << "3" << std::endl;
[ad type=”banner”]

Try this sample code:

bash code
int fd;
char* data = "3";

sync();
fd = open("/proc/sys/vm/drop_caches", O_WRONLY);
write(fd, data, sizeof(char));
close(fd);
[ad type=”banner”]

Clean page cache in linux programmatically
  • You are probably stuck with opening the file /proc/sys/vm/drop_caches, writing 1 to it and close it again. There is no dedicated syscall for that operation.
    bash code
    sync();
    int fd = open("/proc/sys/vm/drop_caches", O_WRONLY);
    write(fd, "1", 1);
    close(fd);

    Depending on what you try to achieve, the (optional) preceding sync() can help free some more memory.

Categorized in: