Skip to content

Instantly share code, notes, and snippets.

@TomNeyland
Created September 3, 2023 03:19
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/9adefc8a06e4cf988b75d7d566ec5b03 to your computer and use it in GitHub Desktop.
Save TomNeyland/9adefc8a06e4cf988b75d7d566ec5b03 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <semaphore.h>
#define SHM_NAME "/my_shared_memory"
#define BUFFER_SIZE 1024
int main() {
int shm_fd;
void *ptr;
sem_t *producer_sem, *consumer_sem;
// Create a shared memory object
shm_fd = shm_open(SHM_NAME, O_CREAT | O_RDWR, 0666);
ftruncate(shm_fd, BUFFER_SIZE);
ptr = mmap(0, BUFFER_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
// Create semaphores
producer_sem = sem_open("/producer_sem", O_CREAT, 0666, 1);
consumer_sem = sem_open("/consumer_sem", O_CREAT, 0666, 0);
// Fork a child process
pid_t pid = fork();
if (pid == 0) {
// Consumer process
while (1) {
sem_wait(consumer_sem);
printf("Consumer received: %s\n", (char *)ptr);
sem_post(producer_sem);
}
} else if (pid > 0) {
// Producer process
while (1) {
sem_wait(producer_sem);
printf("Enter data: ");
fgets((char *)ptr, BUFFER_SIZE, stdin);
sem_post(consumer_sem);
}
} else {
perror("Fork failed");
return 1;
}
// Clean up
sem_close(producer_sem);
sem_close(consumer_sem);
shm_unlink(SHM_NAME);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment