How to programmatically clear the filesystem memor

2019-01-24 11:52发布

I'm writing a benchmark tool in C++ where I want to clear the filesystem memory cache between experiments. I'm aware of the following console commands:

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

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

Any help is appreciated!

3条回答
不美不萌又怎样
2楼-- · 2019-01-24 12:34

Just write to it :

sync();

std::ofstream ofs("/proc/sys/vm/drop_caches");
ofs << "3" << std::endl;
查看更多
叛逆
3楼-- · 2019-01-24 12:34

A slightly better way is to sync just the file systems which contains your descriptors using syncfs(). Or even better, simply use fsync().

int fd = open(...);   // Open your files
write(...);           // Your write calls
fsync(fd);            // Sync your file
close(fd);            // Close them

fsync() can fail if your descriptor is invalid. Look for errno if it returns -1.

查看更多
等我变得足够好
4楼-- · 2019-01-24 12:36

Something like this should do the trick:

int fd;
char* data = "3";

sync();
fd = open("/proc/sys/vm/drop_caches", O_WRONLY);
write(fd, data, sizeof(char));
close(fd);
查看更多
登录 后发表回答