51 lines
1.1 KiB
C++
51 lines
1.1 KiB
C++
/* reader */
|
|
#include<stdio.h>
|
|
#include<sys/mman.h>
|
|
#include<sys/stat.h>
|
|
#include<fcntl.h>
|
|
#include<unistd.h>
|
|
|
|
int main() {
|
|
const char *name = "/my_shared_memory";
|
|
int shm_fd = shm_open(name, O_CREAT | O_RDWR, 0666);
|
|
if (shm_fd == -1) {
|
|
perror("shm_open");
|
|
return 1;
|
|
}
|
|
|
|
// Set the size of the shared memory region
|
|
size_t size = 1024;
|
|
|
|
// Resize the shared memory object to the desired size
|
|
if (ftruncate(shm_fd, size) == -1) {
|
|
perror("ftruncate");
|
|
return 1;
|
|
}
|
|
|
|
// Map the shared memory object into the process address space
|
|
void *ptr = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
|
|
if (ptr == MAP_FAILED) {
|
|
perror("mmap");
|
|
return 1;
|
|
}
|
|
|
|
sleep(2);
|
|
|
|
// Print the contents of the shared memory
|
|
printf("Shared memory contents: %s\n", (char *)ptr);
|
|
|
|
// Unmap the shared memory object
|
|
if (munmap(ptr, size) == -1) {
|
|
perror("munmap");
|
|
return 1;
|
|
}
|
|
|
|
// Close the shared memory file descriptor
|
|
if (close(shm_fd) == -1) {
|
|
perror("close");
|
|
return 1;
|
|
}
|
|
|
|
return 0;
|
|
}
|