Hi members,
This is a program i wanted to implement semaphore between parent and child processes which are trying to access a shared variable called counter ... i dont know why it is not getting incremented during the child process !! someone help please !!
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <semaphore.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
sem_t mutex;
int counter;
int main ()
pid_t child_pid;
sem_init(&mutex, 0, 1);
printf ("the main program process ID is %d\n", (int) getpid ());
child_pid = fork ();
if (child_pid != 0) {
printf ("This is the parent process, with id %d\n", (int) getpid ());
printf("Thread 1: Waiting to enter critical region...\n");
sem_wait(&mutex);
printf("Thread 1: Now in critical region...\n");
printf("Thread 1: Counter Value: %d\n",counter);
printf("Thread 1: Incrementing Counter...\n");
counter++;
printf("Thread 1: New Counter Value: %d\n",counter);
printf("Thread 1: Exiting critical region...\n");
sem_post(&mutex);
}
else
{
sleep(10);
printf ("this is the child process, with id %d\n", (int) getpid ());
sem_wait(&mutex);
printf("Thread 2: Now in critical region...\n");
printf("Thread 2: Counter Value: %d\n",counter);
printf("Thread 2: Incrementing Counter...\n");
counter++;
printf("Thread 2: New Counter Value: %d\n",counter);
printf("Thread 2: Exiting critical region...\n");
sem_post(&mutex);
}
sem_destroy(&mutex);
return 0;
}
haresh.sankarraj 0 Newbie Poster
DeanMSands3 69 Junior Poster
rubberman 1,355 Nearly a Posting Virtuoso Featured Poster
DeanMSands3 commented: Completely missed that. Good eye! +5
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.