11

我需要关于如何编写一个保留指定数量的 MB RAM 的 C 程序的想法,直到一个键 [例如。在 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] 我不知道该怎么做,从命令行获取参数,打印 [任何键被按下] 等等对我来说都不是问题。

关于如何做到这一点的任何想法?

4

5 回答 5

19

您想使用 malloc() 来执行此操作。根据您的需要,您还需要:

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

在大多数现实中, malloc() 和 memset() (或 calloc() 有效地做同样的事情)将满足您的需求。

最后,当然,您希望在不再需要内存时释放()内存。

于 2010-03-08T02:11:31.003 回答
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;
}

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

于 2010-03-08T02:08:19.420 回答
1

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

于 2010-03-08T03:33:37.543 回答
0

这样做,应该工作。尽管我能够保留比我安装的更多的 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;
}
于 2010-03-10T17:38:52.883 回答
0

你会需要:

  • malloc()分配所需的字节数(malloc(200000000)malloc(20 * (1 << 20)))。
  • getc()等待按键。
  • free()释放内存。

这些页面 的信息应该会有所帮助。

于 2010-03-08T02:12:54.167 回答