0
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;
}
3
Contributors
2
Replies
21
Views
3 Years
Discussion Span
Last Post by rubberman
0

These aren't threads; they are processes (because you're using fork). Threads (also called light-weight processes) share the same memory space. Processes do not (until you tell them to).
Now, take a step back and ask yourself: Do I want threads or processes?
If you want threads, use the pthreads library. You will need to yank out the fork command and thread out onto a function then join back.
Have a look at the yolinux article: http://www.yolinux.com/TUTORIALS/LinuxTutorialPosixThreads.html

If you want processes, that's a different story. Have a look at shared memory and IPC. Here's a good place to start:
http://www.advancedlinuxprogramming.com/alp-folder/
Have a look at chapter 3 to get an idea of what's going on, then jump to chapter 5.

Also here: http://www.cs.cf.ac.uk/Dave/C/node27.html

1

What Dean said. Also, the pshared argument to sem_init(sem_t *sem, int pshared, unsigned int value) has to be 1, not 0, to share between processes vs threads.

Votes + Comments
Completely missed that. Good eye!
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.