嵌入式系统节省内存的一种方法

嵌入式系统内存往往是有限制的(成本考虑),因此需要尽量支持更多的功能,同时尽量减少使用的内存。

一种方法是把需要支持的功能做成共享库的形式,需要这个功能的时候加载共享库,不需要的时候卸载共享库,从而把内存释放出来。

下面举个例子说明。

$ cat 1.c 
#include <stdio.h>

static int g_array[1024 * 1024 * 5];
int *g_p = 0;

__attribute__((constructor)) void init1(void) {
    printf("library lib1.so  loaded!\n");
	g_p = (int *)malloc(sizeof(int) * 1024 * 1024 * 5);
	memset(g_p, 0xff, sizeof(int) *1024 * 1024*5);
	memset(g_array, 0xff, sizeof(g_array));
}
 
__attribute__((destructor)) void fini1(void) {
    printf("library lib1.so  unloaded!\n");
	free(g_p);
}
 
	char * str1 = "this is a long text string for testing";
	char * str2 = "this is a long text string for playing";
	char * str3 = "this is a long text string for eating";
	char * str4 = "this is a long text string for laughing";
	char * str5 = "this is a long text string for working";
 
void foo(void)
{
	printf("foo\n");
	printf("%s\n", str1);
	printf("%s\n", str2);
	printf("%s\n", str3);
	printf("%s\n", str4);
	printf("%s\n", str5);
}

$ gcc 1.c -shared -fpic -g -o lib1.so

$ cat test.c 
#include <dlfcn.h>

typedef void (*foo_func)(void );

int main(void)
{
	while( 1)
	{
	void *handle = dlopen("lib1.so", RTLD_LAZY);
	if(handle == 0)
	{
		printf("fail to open lib\n");
		return -1;
	}

	foo_func ff = (foo_func)dlsym(handle, "foo");
	if( ff == 0)
	{
		printf("fail to find ff\n");
		return -1;
	}	

	ff();

	dlclose(handle);
	}
	return 0;
}

$ gcc test.c  -g -o test -ldl -l1 -L.

打开gdb,执行 gdb test,

在dlopen执行前,程序内存使用:

$ ps -p $(pidof test) -o %cpu,%mem,cmd,rss,rsz,vsz,trs
%CPU %MEM CMD                           RSS   RSZ    VSZ  TRS
 0.0  0.0 /home/charles/tmp/test        696   696   2084    1

dlopen()执行后:

$ ps -p $(pidof test) -o %cpu,%mem,cmd,rss,rsz,vsz,trs
%CPU %MEM CMD                           RSS   RSZ    VSZ  TRS
 0.0  1.0 /home/charles/tmp/test      42000 42000  43192    1

dlclose()后:

 ps -p $(pidof test) -o %cpu,%mem,cmd,rss,rsz,vsz,trs
%CPU %MEM CMD                           RSS   RSZ    VSZ  TRS
 0.0  0.0 /home/charles/tmp/test       1092  1092   2216    1

可以看到,大部分用到的内存都释放掉了。

然后如果执行下一次循环, dlopen()后:

$ ps -p $(pidof test) -o %cpu,%mem,cmd,rss,rsz,vsz,trs
%CPU %MEM CMD                           RSS   RSZ    VSZ  TRS
 0.0  1.0 /home/charles/tmp/test      42008 42008  43192    1

执行 dlclose()后:

$ ps -p $(pidof test) -o %cpu,%mem,cmd,rss,rsz,vsz,trs
%CPU %MEM CMD                           RSS   RSZ    VSZ  TRS
 0.0  0.0 /home/charles/tmp/test       1092  1092   2216   

内存又恢复到上次的数值了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值