Skip to content

Instantly share code, notes, and snippets.

@TomNeyland
Created September 1, 2023 02:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TomNeyland/97b881a7fbe84744d97d646b38da830b to your computer and use it in GitHub Desktop.
Save TomNeyland/97b881a7fbe84744d97d646b38da830b to your computer and use it in GitHub Desktop.
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <pthread.h>
typedef struct {
pthread_mutex_t mutex;
char data[100];
} SharedMemory;
int main() {
int shm_fd;
SharedMemory *shared_memory;
// Create the shared memory object
shm_fd = shm_open("my_shm", O_CREAT | O_RDWR, 0666);
if (shm_fd == -1) {
perror("Failed to create shared memory");
exit(EXIT_FAILURE);
}
// Configure the size of the shared memory object
ftruncate(shm_fd, sizeof(SharedMemory));
// Map the shared memory object
shared_memory = (SharedMemory *) mmap(NULL, sizeof(SharedMemory), PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
if (shared_memory == MAP_FAILED) {
perror("Failed to map shared memory");
exit(EXIT_FAILURE);
}
// Initialize the mutex
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
pthread_mutex_init(&shared_memory->mutex, &attr);
// Fork a process
pid_t pid = fork();
if (pid < 0) {
perror("Fork failed");
exit(EXIT_FAILURE);
}
if (pid == 0) { // Child (Consumer)
for (int i = 0; i < 5; i++) {
pthread_mutex_lock(&shared_memory->mutex);
printf("Consumer read: %s\n", shared_memory->data);
pthread_mutex_unlock(&shared_memory->mutex);
sleep(1);
}
} else { // Parent (Producer)
for (int i = 0; i < 5; i++) {
pthread_mutex_lock(&shared_memory->mutex);
snprintf(shared_memory->data, sizeof(shared_memory->data), "Data %d", i + 1);
printf("Producer wrote: %s\n", shared_memory->data);
pthread_mutex_unlock(&shared_memory->mutex);
sleep(1);
}
}
// Cleanup
pthread_mutex_destroy(&shared_memory->mutex);
munmap(shared_memory, sizeof(SharedMemory));
close(shm_fd);
shm_unlink("my_shm");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment