在C中保留RAM

我需要关于如何编写一个C程序来保留指定数量的MB RAM的想法,直到一个键[例如, 在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. * 

这是程序的核心function[保留RAM]我不知道该怎么做,从命令行获取参数,打印[任意键被按下]等都不是我的问题。

任何想法如何做到这一点?

你想用malloc()来做到这一点。 根据您的需要,您还需要:

  1. 将数据写入内存,以便内核实际保证它。 你可以为此使用memset()。
  2. 防止内存被换出(交换),mlock()/ mlockall()函数可以帮助你做到这一点。
  3. 告诉内核你实际上打算如何使用内存,这是通过posix_madvise()完成的(这比明确的mlockall()更好)。

在大多数情况下,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; } 

如果你想了解更多的信息,可以看一下手册页(linux shell中的man malloc )。 如果您不在Linux上,请查看在线手册页 。

calloc()是你想要的。 它会为你的进程保留内存,并写入零。 这确保内存实际上分配给您的进程。 如果你malloc()大部分的内存,操作系统可能是懒惰的实际分配内存给你,只有实际上分配它写入时(这将不会发生在这种情况下)。

你会需要:

  • malloc()分配无论你需要多少字节( malloc(200000000)malloc(20 * (1 << 20)) )。
  • getc()等待按键。
  • free()来释放内存。

这些 页面 上的信息应该是有帮助的。

这是否应该工作? 尽管我能够预留比我安装的更多的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; }