From 7fe01720affe967ce610ef69993adfbfd456c542 Mon Sep 17 00:00:00 2001 From: ItsMAX0112 Date: Mon, 21 Oct 2024 01:28:43 +0530 Subject: [PATCH] trying shm --- lab4/src/shm1.cpp | 53 +++++++++++++++++++++++++++++++++++++++++++++++ lab4/src/shm2.cpp | 50 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 103 insertions(+) create mode 100644 lab4/src/shm1.cpp create mode 100644 lab4/src/shm2.cpp diff --git a/lab4/src/shm1.cpp b/lab4/src/shm1.cpp new file mode 100644 index 0000000..fa004a1 --- /dev/null +++ b/lab4/src/shm1.cpp @@ -0,0 +1,53 @@ +#include +#include +#include +#include +#include + +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; + } + + // Write data to the shared memory + sprintf(ptr, "Hello, shared memory!"); + + // 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; + } + + // Unlink the shared memory object + if (shm_unlink(name) == -1) { + perror("shm_unlink"); + return 1; + } + + return 0; +} diff --git a/lab4/src/shm2.cpp b/lab4/src/shm2.cpp new file mode 100644 index 0000000..aec2d26 --- /dev/null +++ b/lab4/src/shm2.cpp @@ -0,0 +1,50 @@ +/* reader */ +#include +#include +#include +#include +#include + +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; +}