[英]Reserve RAM in C
我需要有关如何编写一个C程序的想法,该程序保留指定数量的MB RAM直到一个键[ex。 在Linux 2.6 32位系统上按下任意键。
*
/.eat_ram.out 200
# If free -m is execute at this time, it should report 200 MB more in the used section, than before running the program.
[Any key is pressed]
# Now all the reserved RAM should be released and the program exits.
*
它是程序的核心功能[保留RAM]我不知道怎么做,从命令行获取参数,打印[按任意键]等等对我来说不是问题。
关于如何做到这一点的任何想法?
您想使用malloc()来执行此操作。 根据您的需要,您还需要:
在大多数情况下,malloc()和memset()(或者有效地执行相同操作的calloc())将满足您的需求。
最后,当然,你想在不再需要时释放()内存。
你不能只使用malloc()
将ram分配给你的进程吗? 那将为你保留RAM,然后你就可以自由地做任何你想做的事了。
这是给你的一个例子:
#include <stdlib.h>
int main (int argc, char* argv[]) {
int bytesToAllocate;
char* bytesReserved = NULL;
//assume you have code here that fills bytesToAllocate
bytesReserved = malloc(bytesToAllocate);
if (bytesReserved == NULL) {
//an error occurred while reserving the memory - handle it here
}
//when the program ends:
free(bytesReserved);
return 0;
}
如果您想了解更多信息,请查看手册页(linux shell中的man malloc
)。 如果您不在Linux上,请查看在线手册页 。
calloc()
就是你想要的。 它将为您的进程保留内存并向其写入零。 这可确保为您的进程实际分配内存。 如果malloc()
占用了很大一部分内存,那么操作系统可能会为你实际分配内存而懒,只有在写入时才实际分配(在这种情况下永远不会发生)。
这是否应该有效。 虽然我能够保留比我安装的RAM更多的RAM,但这应该适用于有效值。
#include <stdio.h>
#include <stdlib.h>
enum
{
MULTIPLICATOR = 1024 * 1024 // 1 MB
};
int
main(int argc, char *argv[])
{
void *reserve;
unsigned int amount;
if (argc < 2)
{
fprintf(stderr, "usage: %s <megabytes>\n", argv[0]);
return EXIT_FAILURE;
}
amount = atoi(argv[1]);
printf("About to reserve %ld MB (%ld Bytes) of RAM...\n", amount, amount * MULTIPLICATOR);
reserve = calloc(amount * MULTIPLICATOR, 1);
if (reserve == NULL)
{
fprintf(stderr, "Couldn't allocate memory\n");
return EXIT_FAILURE;
}
printf("Allocated. Press any key to release the memory.\n");
getchar();
free(reserve);
printf("Deallocated reserved memory\n");
return EXIT_SUCCESS;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.