Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reserve RAM in C

Tags:

c

linux

memory

ram

I need ideas on how to write a C program that reserve a specified amount of MB RAM until a key [ex. the any key] is pressed on a Linux 2.6 32 bit system.

*
/.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.
*

It is the core functionality of the program [reserving the RAM] i do not know how to do, getting arguments from the commandline, printing [Any key is pressed] and so on is not a problem from me.

Any ideas on how to do this?

like image 665
petersmith221 Avatar asked Mar 08 '10 02:03

petersmith221


1 Answers

You want to use malloc() to do this. Depending on your need, you will also want to:

  1. Write data to the memory so that the kernel actually guarantees it. You can use memset() for this.
  2. Prevent the memory from being paged out (swapped), the mlock() / mlockall() functions can help you with this.
  3. Tell the kernel how you actually intend to use the memory, which is accomplished via posix_madvise() (this is preferable to an explicit mlockall()).

In most realities, malloc() and memset() (or, calloc() which effectively does the same) will suit your needs.

Finally, of course, you want to free() the memory when it is no longer needed.

like image 52
Tim Post Avatar answered Oct 27 '22 06:10

Tim Post