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. 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!


Just write to it :

sync();

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


int fd;
char* data = "3";

sync();
fd = open("/proc/sys/vm/drop_caches", O_WRONLY);
write(fd, data, sizeof(char));
close(fd);

This is a better answer because it includes a sync. Which is important because drop_caches is a debuggingtool and it does not always get the data on disk before dropping it. –   Zan Lynx  Jul 25 '11 at 15:54
 
A better answer that what? Both of the answers I see include a sync. –   James Kanze  Jul 25 '11 at 16:12
 
@James : Mine was edited. –   kbok  Jul 25 '11 at 22:09
 
If that's true then this is a bit dangerous - what happens if a process writes a file in the background? Is the data written between sync() and open() just lost? –   Malvineous  Jun 17 '12 at 12:33
 
@ZanLynx: drop_caches is non-destructive and will only free clean caches (ones that have not been synced to disk). Thus calling sync() before doesn't make the operation any more safe, but rather increases the number of caches that can be dropped. See: /usr/src/linux/Documentation/sysctl/vm.txt –   kalaxy  Oct 10 '12 at 22:40
 
@kalaxy: When I used to run -mm kernels in 2008 it was definitely not safe. –   Zan Lynx  Oct 10 '12 at 22:51
 
If drop_caches is unsafe, your kernel is bugged. No modern kernel will have a problem with this. –  Paul Betts  Oct 10 '12 at 23:50



自己编写代码如下: 

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#define TRUE 1
#define FALSE 0

typedef unsigned int INT32U;
typedef unsigned char INT8U;



INT8U Get_SysCachedMem(INT32U *cachedmem_size);
INT8U Clean_SysCachedMem(void);

int main(void)
{
	INT32U cachedmem_size;
	Get_SysCachedMem(&cachedmem_size);
	printf("cachedmem_size = %d\n", cachedmem_size);
	
	Clean_SysCachedMem();
		
	Get_SysCachedMem(&cachedmem_size);
	printf("cachedmem_size = %d\n", cachedmem_size);
	
	
	return 0;
}

INT8U Get_SysCachedMem(INT32U *cachedmem_size)
{
	char 	buffer[128];
	char 	args01[64];
	INT32U  args02;
	char 	args03[64];
	FILE 	*fp = NULL;
	INT8U	isGetCachedArgs = FALSE;
	
	fp = fopen("/proc/meminfo", "r");
	fseek(fp, 0, SEEK_SET);
	
	//从/proc/meminfo文件中一行一行过滤出cached参数
	memset(buffer, 0, sizeof(buffer));
	while (fgets(buffer, sizeof(buffer), fp) != NULL) 
	{
		sscanf(buffer, "%s\t%ld%s", args01, &args02, args03);
		printf("buffer = %s %d %s\n", args01, args02, args03);
	
		if(strncmp(args01, "Cached:", strlen("Cached:")) == 0)
		{
			isGetCachedArgs = TRUE;
			break;
		}
		
		memset(buffer, 0, sizeof(buffer));
	}
	fclose(fp);
	
	if( !isGetCachedArgs )
	{
		*cachedmem_size = 0;
		return FALSE;
	}
	
	*cachedmem_size = args02;
	
	return TRUE;
}

INT8U Clean_SysCachedMem(void)
{
	int fd;
	const char* data = "3";

	sync();
	fd = open("/proc/sys/vm/drop_caches", O_WRONLY);
	if(fd < 0)
	{
		return FALSE;
	}
	
	write(fd, data, sizeof(char));
	close(fd);

	return TRUE;
}


测试已通过



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python is an ideal language for solving problems, especially in Linux and Unix networks. With this pragmatic book, administrators can review various tasks that often occur in the management of these systems, and learn how Python can provide a more efficient and less painful way to handle them., Each chapter in Python for Unix and Linux System Administration presents a particular administrative issue, such as concurrency or data backup, and presents Python solutions through hands-on examples. Once you finish this book, you'll be able to develop your own set of command-line utilities with Python to tackle a wide range of problems. Discover how this language can help you:, * Read text files and extract information, * Run tasks concurrently using the threading and forking options, * Get information from one process to another using network facilities, * Create clickable GUIs to handle large and complex utilities, * Monitor large clusters of machines by interacting with SNMP programmatically, * Master the IPython Interactive Python shell to replace or augment Bash, Korn, or Z-Shell, * Integrate Cloud Computing into your infrastructure, and learn to write a Google App Engine Application, * Solve unique data backup challenges with customized scripts, * Interact with MySQL, SQLite, Oracle, Postgres, Django ORM, and SQLAlchemy, With this book, you'll learn how to package and deploy your Python applications and libraries, and write code that runs equally well on multiple Unix platforms. You'll also learn about several Python-related technologies that will make your life much easier.
The Definitive Guide to JSF in Java EE 8 pdf Learn and master the new features in the JSF 2.3 MVC web framework in this definitive guide written by two of the JavaServer Faces (JSF) specification leads. The authors take you through real-world examples that demonstrate how these new features are used with other APIs in Java EE 8. You’ll see the new and exciting ways JSF applications can use to communicate between a client and a server, such as using WebSockets, invoking bean methods directly from Ajax, executing client-side JavaScript when Ajax calls complete, and more Along the way you’ll broaden your knowledge of JSF components and web APIs best practices, and learn a great deal about the internals of JSF and the design decisions that have been made when building the JSF API. For example, you’ll see what artefacts are now CDI injectable, how CDI changed JSF internally, and what some of the caveats are when working with the CDI versions of a JSF artefact. Furthermore, you'll build an example application from scratch. After reading The Definitive Guide to JSF in Java EE 8, you'll be ready to build your own efficient and secure web applications. What You Will Learn Leverage the new features in JSF 2.3 in your existing applications Integrate JSF and CDI Use the brand new Component Search Expression framework, which enables you to more easily locate components from your template Extend the Component Search Expression framework with your own search operators Work with the different ways of mapping requests to JSF, make your application use extensionless URLs, and programmatically inspect which resources are present in your application Master the best practices for web application development and see which are obsolete Who This Book Is For Existing JSF or Java developers who need to create a web UI. No prior knowledge of JSF is required, but the book does skew towards the more experienced developer. Concepts such as dependency injection and MVC are assumed to be known, as is a general knowledge about HTML, HTTP and other web standards.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值