Created
September 3, 2023 03:19
-
-
Save TomNeyland/ca22acebb8ccbeaa495d7b52e8003962 to your computer and use it in GitHub Desktop.
Mutex3dot5.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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