setrlimit測試程序

#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/resource.h>

char cmd[32];
 
int print_mem_used()
{
	FILE *fpRead;
	char data_buf[32];
	
	fpRead = popen(cmd, "r");
	
	if(NULL == fpRead)
	{
		printf("fpRead error%d,%s\n", errno, strerror(errno));
		return -1;
	}

	memset(data_buf, 0, sizeof(data_buf));
	if(NULL == fgets(data_buf, sizeof(data_buf)-1, fpRead))
	{
		printf("fgets is null\n");
		return -1;
	}
	
	printf("current used mem(kB): %s", data_buf);
	pclose(fpRead);
	
	return 0;
}

void print_rlim_value(struct rlimit *limit)
{
	printf("soft:[%lu kB]		hard:[%lu kB]\n", (unsigned long)limit->rlim_cur/1024, (unsigned long)limit->rlim_max/1024);
}

int main(void)
{
	int self_pid = -1;
	struct rlimit memoryL;
	unsigned long limt = 0;
	
	sprintf(cmd, "cat /proc/%d/status | grep VmSize | awk '{print $2}'", (int)getpid());
	printf("---------------------------------------\n");
	if(0 != print_mem_used())
	{
		return -1;
	}
	
	getrlimit(RLIMIT_AS, &memoryL);
	printf("\nCurrent system rlimit:\n");
	print_rlim_value(&memoryL);
 
	printf("\nPlease input new limit(kB, must bigger than current used mem and can be divisible by 4),0 to exit: ");
	scanf("%lu",&limt);
	if(0 != limt%4 || 0 == limt)
	{
		printf("Can't be divisible by 4.\n");
		return 0;
	}
	memoryL.rlim_cur = limt*1024;
	memoryL.rlim_max = limt*1024;
	setrlimit(RLIMIT_AS ,&memoryL);
	
	getrlimit(RLIMIT_AS, &memoryL);
	printf("\nSystem rlimit after setrlimit:\n");
	print_rlim_value(&memoryL);
	
	if(limt*1024 != memoryL.rlim_cur || limt*1024 != memoryL.rlim_max)
	{
		printf("setrlimit faild\n");
		return -1;
	}

	printf("\nMalloc 4kB each time:\n---------------------------------------\n");
	
	while(1)
	{
		errno  = 0;
		char *psString = (char *)malloc(4*1024*sizeof(char)); //4kB,4字節對齊
		if(NULL == psString)
		{
			printf("errno=%d(%s), ENOMEM=%d\n---------------------------------------\n", errno, strerror(errno), ENOMEM);
			printf("Last time you set rlimit:\n");
			print_rlim_value(&memoryL);
			break;
		}
		else
		{
			printf("malloc %d success, ", 4*1024*sizeof(char));
			if(0 != print_mem_used())
			{
				return -1;
			}
		}
	}
	printf("---------------------------------------\n");
	
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章