In my application I need to share memory
between parent and child (using fork
+execl
).
I use memfd_create
to allocate memory, because it provides a
file descriptor, which may be conveniently used in child
process (the discriptor is tied to stdin via dup2
before execl
)
to attach to the allocated memory.
I do not use write
and read
- I use pointers
to read and write memory directly.
The only piece of the puzzle which is left to solve
is how to get the address of memory, allocated
via fd = memfd_create ...
.
Using mmap
is undesirable, because it duplicates the memory, instead of giving the
memory address already allocated by memfd_create
.
This is demonstrated by the following code.
In its output each mmap
address is incremented by 4096
, which is the size of memory, referred to by fd
:
0x7f98411c1000
0x7f98411c0000
whereas if mmap
had given the direct address,
addresses in the output would be the same.
#include <stdio.h>
#include <sys/mman.h>
#include <sys/syscall.h>
#include <unistd.h>
int main(void)
{
int fd = syscall(SYS_memfd_create, "shm", 0);
if (fd == -1) return 1;
size_t size = 4096; /* minimal */
int check = ftruncate(fd, size);
if (check == -1) return 1;
void *ptr = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (ptr == MAP_FAILED) return 1;
void *ptr2 = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (ptr2 == MAP_FAILED) return 1;
printf("%p\n%p\n", ptr, ptr2);
return 0;
}
So, how to get direct address, avoiding memory duplication
by mmap
?