pet*_*221 10 c linux memory ram
我需要有关如何编写一个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.
*
Run Code Online (Sandbox Code Playgroud)
它是程序的核心功能[保留RAM]我不知道怎么做,从命令行获取参数,打印[按任意键]等等对我来说不是问题.
关于如何做到这一点的任何想法?
Tim*_*ost 19
您想使用malloc()来执行此操作.根据您的需要,您还需要:
在大多数情况下,malloc()和memset()(或者有效地执行相同操作的calloc())将满足您的需求.
最后,当然,你想在不再需要时释放()内存.
您不能直接malloc()将该内存分配给您的进程吗?这将为您保留 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;
}
Run Code Online (Sandbox Code Playgroud)
如果您想了解更多信息,请查看手册页(man malloc在 Linux shell 中)。如果您使用的不是 Linux,请查看在线手册页。