Reputation: 3408
I invoke mprotect
frequently in my program, and I find the program fails after a while. I guess it is due to too many mprotect
calls, So I wrote a test to verify:
#define pagesize 4096
int main(){
while(1){
buffer = memalign(pagesize, 4 * pagesize);// allocate some buffer
mprotect(buffer, pagesize, PROT_NONE)// make the first page inaccessible
}
}
After around 30 thousand iterations, mprotect returns -1, regardless of the size of the buffer.
Can anybody explain why and how to resolve it? My guess is mprogtect consumes kernel resources and there is some constraint for each process, but not sure.
Upvotes: 6
Views: 1858
Reputation: 7585
Apparently, there's a kernel parameter controlling the number of distinct mappings a process can have, available at /proc/sys/vm/max_map_count
. The typical default number of mappings on most distros is 64k - consistent with mprotect
failing at around 30k iterations (one mapping per memalign
, another per mprotect
+ some normal system mappings). Increasing that limit will allow you to allocate and protect more memory areas.
Upvotes: 7