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");
printf("Thread 1: Now in critical region...\n");
    printf("Thread 1: Counter Value: %d\n",counter);
    printf("Thread 1: Incrementing Counter...\n");
    printf("Thread 1: New Counter Value: %d\n",counter);
    printf("Thread 1: Exiting critical region...\n");
printf ("this is the child process, with id %d\n", (int) getpid ());
printf("Thread 2: Now in critical region...\n");
    printf("Thread 2: Counter Value: %d\n",counter);
    printf("Thread 2: Incrementing Counter...\n");
    printf("Thread 2: New Counter Value: %d\n",counter);
    printf("Thread 2: Exiting critical region...\n");
return 0;

Recommended Answers

All 2 Replies

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:
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

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.

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, learning, and sharing knowledge.