10

Using getrlimit(RLIMIT_MEMLOCK), one can get the allowed amount of locked memory a process can allocate (mlock() or mlockall()).

But how to retrieve the currently locked memory amount ?

For example, there's no information returned by getrusage().

Under Linux, it is possible to read /proc/self/status and extract the amount of locked memory from the line beginning with VmLck.

Is there a portable way to retrieve the amount of locked memory which would work on Linux, *BSD and other POSIX compatible systems ?

Yann Droneaud
  • 5,277
  • 1
  • 23
  • 39
  • 1
    POSIX specifies that calls to mlock and mlockall will fail with ENOSYS if the call is not implemented. This means there is no guaranteed portable interface for locking/unlocking, portable in the sense that it is guaranteed to be implemented. Also. There is no POSIX specified way to enumerate locked pages of process memory. – jim mcnamara Apr 25 '11 at 18:22

1 Answers1

3

You will probably need to check for each system and implement it accordingly. On Linux:

cat /proc/$PID/status | grep VmLck

You will probably need to do the same in C (read /proc line by line and search for VmLck), as this information is created in the function task_mem (in array.c) which I don't think you can access directly. Something like:

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

char cwd[PATH_MAX];
sprintf(cwd, "/proc/%d/status", getpid());

FILE* fp = fopen(cwd, "r");
if(!fp) {
    exit(EXIT_FAILURE);
}

while((read = getline(&line, &len, fp)) != -1) {
    // search for line starting by "VmLck"
}
Giovanni Funchal
  • 8,934
  • 13
  • 61
  • 110