I need to use a shared memory between processes and I found a sample code here. First of all, I need to learn how to create a shared memory block and store a string in it. To do that I used following code:
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <string.h>
#include <unistd.h>
void* create_shared_memory(size_t size) {
// Our memory buffer will be readable and writable:
int protection = PROT_READ | PROT_WRITE;
// The buffer will be shared (meaning other processes can access it), but
// anonymous (meaning third-party processes cannot obtain an address for it),
// so only this process and its children will be able to use it:
int visibility = MAP_ANONYMOUS | MAP_SHARED;
// The remaining parameters to `mmap()` are not important for this use case,
// but the manpage for `mmap` explains their purpose.
return mmap(NULL, size, protection, visibility, 0, 0);
}
int main() {
char msg[] = "hello world!";
void* shmem = create_shared_memory(1);
printf("sizeof shmem: %lu\n", sizeof(shmem));
printf("sizeof msg: %lu\n", sizeof(msg));
memcpy(shmem, msg, sizeof(msg));
printf("message: %s\n", shmem);
}
Output:
sizeof shmem: 8
sizeof msg: 13
message: hello world!
In main function, I'm creating 1 byte shared memory block (shmem
) and trying to store 13 byte information (char msg[]
) in it. When I print out the shmem
, it prints whole message. I'm expecting that, it prints out just 1 byte message in this case is just "h"
. Or it could give an error about memory size when compiled.
The question is that I'm missing sth here? Or is there a implementation issue? Does memcpy
overlap here? I'm appreciated for any brief explanation.
Thanks in advance.