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

[pastacode lang=”bash” manual=”sync%0Aecho%203%20%3E%20%2Fproc%2Fsys%2Fvm%2Fdrop_caches%0A” message=”bash code” highlight=”” provider=”manual”/]

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

Try this :

[pastacode lang=”bash” manual=”sync()%3B%0A%0Astd%3A%3Aofstream%20ofs(%22%2Fproc%2Fsys%2Fvm%2Fdrop_caches%22)%3B%0Aofs%20%3C%3C%20%223%22%20%3C%3C%20std%3A%3Aendl%3B%0A” message=”bash code” highlight=”” provider=”manual”/] [ad type=”banner”]

Try this sample code:

[pastacode lang=”bash” manual=”int%20fd%3B%0Achar*%20data%20%3D%20%223%22%3B%0A%0Async()%3B%0Afd%20%3D%20open(%22%2Fproc%2Fsys%2Fvm%2Fdrop_caches%22%2C%20O_WRONLY)%3B%0Awrite(fd%2C%20data%2C%20sizeof(char))%3B%0Aclose(fd)%3B%0A” message=”bash code” highlight=”” provider=”manual”/] [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.[pastacode lang=”bash” manual=”sync()%3B%0Aint%20fd%20%3D%20open(%22%2Fproc%2Fsys%2Fvm%2Fdrop_caches%22%2C%20O_WRONLY)%3B%0Awrite(fd%2C%20%221%22%2C%201)%3B%0Aclose(fd)%3B%0A” message=”bash code” highlight=”” provider=”manual”/]

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

Categorized in: