user683595
user683595

Reputation: 407

How can we allocate a buffer that we are sure won't be paged?

Maybe this one thing is related to buffer allocation in kernel.
Suppose we want to write a music player, if paging happens, this may lead to choppy low quality music playing.
Video Player, we want to write a real time software, or anything.
We want to assign one of the CPUs to a process, or we make a process very high priority, and then we want to make sure our buffer won't be paged to HDD. How is it done in C and Linux?

Upvotes: 5

Views: 150

Answers (1)

Fingolfin
Fingolfin

Reputation: 5533

By calling:

int mlock(const void *addr, size_t len);//included in header #include <sys/mman.h>

with the start address of the area and its length, the system will guarantee that the memory specified will reside in RAM until you call

int munlock(const void *addr, size_t len);

You can also call the function mlockall(MCL_FUTURE); which will make all your following memory allocations be RAM residents but this poses the risk of allocating more than what's physically available and the result is implementation dependent.

EDIT: For more details, check the following links: http://pubs.opengroup.org/onlinepubs/007908799/xsh/mlock.html
http://pubs.opengroup.org/onlinepubs/007908799/xsh/mlockall.html

EDIT2: Zan Lynx's comment
Also note that using this to lock more than 64KB (on most Linux systems) will require root privileges. Best way in my opinion is to have a wrapper that launches as root, sets up relaxed real-time and memory lock requirements, switches user IDs and then runs the actual program.


**P.S** Normally when RT requirments arise, not only you lock your program in RAM but you also set the scheduler into real-time mode, for that you can check `sched_setscheduler(..)`

Upvotes: 10

Related Questions