shared-memory-in-c/forking/main.c

63 lines
1.4 KiB
C

#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <pthread.h>
#include <stdbool.h>
#include <time.h>
struct shared_data {
pthread_mutex_t mutex;
int counter;
};
void increment_counter(const char *name, struct shared_data *data) {
for (int i = 0; i < 10000; i++) {
if (pthread_mutex_lock(&data->mutex) != 0) {
perror("pthread_mutex_lock");
}
data->counter++;
if (pthread_mutex_unlock(&data->mutex) != 0) {
perror("pthread_mutex_unlock");
}
}
}
int main() {
struct shared_data *shared_data = mmap(NULL, sizeof(struct shared_data), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
if (shared_data == NULL) {
perror("mmap");
return -1;
}
pthread_mutexattr_t mutex_attr;
pthread_mutexattr_init(&mutex_attr);
pthread_mutexattr_setpshared(&mutex_attr, PTHREAD_PROCESS_SHARED);
if (pthread_mutex_init(&shared_data->mutex, &mutex_attr) < 0) {
printf("Failed to initialise mutex\n");
return -1;
}
shared_data->counter = 0;
int pid = fork();
if (pid == 0) {
srand(time(NULL)+1);
increment_counter("Child ", shared_data);
return 0;
} else {
srand(time(NULL)+2);
increment_counter("Parent", shared_data);
}
int child_status;
waitpid(pid, &child_status, 0);
printf("Counter is %d\n", shared_data->counter);
}