I am trying to create 4 child processes from the main process and in turn the child process will go into critical region lock it and increase the variable counter
when all processes end final counter is printed
in the given code below i am unable to increase the counter
PS: I have read some posts on unnamed semaphores and have seen some posts on stack overflow. either they don't resolve my issue or they are examples of threads and semaphores and not child processes and semaphores
Also i insist on using unnamed semaphore since i am new to this i might be doing some foolish mistake.
#include<stdio.h>
#include<sys/wait.h>
#include<sys/types.h>
#include<semaphore.h>
#include<unistd.h>
#include<stdlib.h>
sem_t mutex;
int counter = 1;
void child(int id){
// critical region
sem_wait(&mutex);
printf("Counter right now for %d is %d\n" , id, counter);
printf("Increasing counter for %d\n", id);
(counter)++;
printf("Counter now for %d is %d\n", id, counter);
sem_post(&mutex);
}
int main(){
pid_t pid;
sem_init(&mutex, 1, 1);
for(int kid = 1; kid < 5; kid++){
pid = fork();
if(pid==0){
child(kid);
printf("Counter after child %d is %d\n\n", kid, counter);
exit(0);
}
else{
printf("parent process %d with counter = %d\n\n", kid, counter);
}
}
int status;
for(int kid=1; kid<5; kid++){
wait(&status);
}
printf("final counter is %d\n", counter);
sem_destroy(&mutex);
}
the output i am getting is 1 the output i am expecting is 5