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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With