在C中保留RAM

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()来执行此操作.根据您的需要,您还需要:

  1. 将数据写入内存,以便内核实际保证它.你可以使用memset().
  2. 防止内存被分页(交换),mlock()/ mlockall()函数可以帮助你解决这个问题.
  3. 告诉内核你实际打算如何使用内存,这是通过posix_madvise()完成的(这比显式的mlockall()更好).

在大多数情况下,malloc()和memset()(或者有效地执行相同操作的calloc())将满足您的需求.

最后,当然,你想在不再需要时释放()内存.


a_m*_*m0d 3

您不能直接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,请查看在线手册页

  • 动态分配对于这个人来说可能是新的......你应该真正解释它,或者至少提供一个像样的教程的链接。 (2认同)