Reputation: 919
I have 3 tools and I need them to share the same first 4096 bytes of their own memory. Each tool can increase their memory independently.
So a resume:
tool1:
0 - 4096 :shared between 1,2,3
4097 - 8192 : internal to 1
tool2:
0 - 4096 :shared between 1,2,3
4097 - 16384 : internal to 2
tool3:
0 - 4096 :shared between 1,2,3
4097 - 12288 : internal to 3
Is it possible to use mmap to achieve my goal because I prefer mmap ? If another solution is available, maybe I could adapt my code.
Thank you in advance for your help.
Upvotes: 2
Views: 437
Reputation: 3597
There are serious security and maintainability issues with mapping and using the first page of virtual memory, but you can do it if you really want.
First you need to adjust a sysctl that prevents you from doing things like this (for good reason):
sudo sysctl -w vm.mmap_min_addr=0
Then use mmap
as you normally would for shared memory, but with MAP_FIXED
. Now you can read and write to the first page (including the NULL pointer):
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
int main()
{
int fd = shm_open("silly_example", O_RDWR | O_CREAT, 0600);
mmap(0, 4096, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, fd, 0);
ftruncate(fd, 4096);
int *ptr = (int*) 0;
*ptr = 123;
printf("%d\n", *ptr);
getchar();
}
You can verify that the mapped is created:
$ cat /proc/17444/maps
00000000-00001000 rw-s 00000000 00:12 41774576 /dev/shm/silly_example
All processes mapping the shared file in this way will share the 4096 bytes of memory (mapped to the zero-page). I used POSIX shared memory in this example, but you can use any file as long as you truncate it to 4096 bytes.
You should seriously consider what you are trying to do, and if this is really necessary.
Upvotes: 2