简体   繁体   English

如何在Linux系统上以编程方式清除C ++中的文件系统内存缓存?

[英]How to programmatically clear the filesystem memory cache in C++ on a Linux system?

I'm writing a benchmark tool in C++ where I want to clear the filesystem memory cache between experiments. 我正在用C ++编写一个基准测试工具,我希望在实验之间清除文件系统内存缓存。 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++? 我的问题是如何在C ++中直接以编程方式执行此操作?

Any help is appreciated! 任何帮助表示赞赏!

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);

Just write to it : 写信给它:

sync();

std::ofstream ofs("/proc/sys/vm/drop_caches");
ofs << "3" << std::endl;

A slightly better way is to sync just the file systems which contains your descriptors using syncfs() . 稍微好一点的方法是使用syncfs()同步包含描述符的文件系统。 Or even better, simply use fsync() . 或者甚至更好,只需使用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. 如果描述符无效, fsync()可能会失败。 Look for errno if it returns -1 . 如果它返回-1则查找errno

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM