Skip to content

Instantly share code, notes, and snippets.

@JackyYin
Created October 30, 2021 07:18
Show Gist options
  • Save JackyYin/66e0c198e9f9cdf7314d8e276dc86990 to your computer and use it in GitHub Desktop.
Save JackyYin/66e0c198e9f9cdf7314d8e276dc86990 to your computer and use it in GitHub Desktop.
Test RLIMIT_MEMLOCK and mlock behavior.
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/mman.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
int main() {
long page_sz = sysconf(_SC_PAGESIZE);
printf("page size: %lu\n", page_sz);
const struct rlimit mlock_rlimit = {
.rlim_cur = page_sz,
.rlim_max = page_sz,
};
if ((setrlimit(RLIMIT_MEMLOCK, &mlock_rlimit))) {
printf("setrlimit error: %s\n", strerror(errno));
}
const long mem_sz = page_sz * 2;
void *ptr;
if ((posix_memalign(&ptr, page_sz, mem_sz))) {
printf("posix_memalign error: %s\n", strerror(errno));
}
if (mlock(ptr, mem_sz)) {
printf("mlock error: %s\n", strerror(errno));
}
return 0;
}
@JackyYin
Copy link
Author

JackyYin commented Oct 30, 2021

expected result:

page size: 4096
mlock error: Resource temporarily unavailable

explaination: mlock will fail to lock a block of memory space larger than the resouce limit.

   ENOMEM (Linux 2.6.9 and later) the caller had a nonzero
       RLIMIT_MEMLOCK soft resource limit, but tried to lock more
       memory than the limit permitted.  This limit is not
       enforced if the process is privileged (CAP_IPC_LOCK).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment