0

I am working on a project that requires process synchronization. The problem I have is that the samaphore I use does not seem to be shared across all processes. It behaves similar to local variable. This is a simplified code, but demonstrates the same problem:

#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
#include <time.h>
#include <semaphore.h>
#include <fcntl.h>


sem_t sem_1;    //Global variable (semaphore).

int main(){
    sem_init(&sem_1, 1, 0);     //semaphore starts with 0           
    pid_t child_pid_or_zero = fork();   //process fork
    if (child_pid_or_zero < 0){     
        perror("fork() error");
        exit (2);
    }

    if (child_pid_or_zero != 0){
        sem_wait(&sem_1);           //decrement to -1 and waits 
        printf("I am the parent %d, my child is %d.\n",getpid(),child_pid_or_zero);

    }else{

        printf("i am child\n");
        sem_post(&sem_1);       //increments
    }   
return 0;
}

The parent process never gets over the wait signal. I tried adding mupltiple sem_post() to both processes and print the values with sem_getvalue() and the numbers printed seemed not to be shared (every processs incremented its own semaphore).

Thanks for help.

Jakub Svoboda
  • 100
  • 11
  • 2
    After a `fork` the parent and child have seperate address spaces. They are exact (more or less) copies of the address space immediately after the `fork` but any subsequent changes to one are not seen by the other. – kaylum Apr 15 '16 at 11:24
  • 1
    Read the `sem_init` man page or see questions like [How to share semaphores between processes using shared memory](http://stackoverflow.com/questions/8359322/how-to-share-semaphores-between-processes-using-shared-memory?rq=1) – kaylum Apr 15 '16 at 11:28

2 Answers2

1

POSIX is quite unclear how the pshared argument (second argument) to sem_init works. The Linux man page explains it better:

If pshared is nonzero, then the semaphore is shared between processes, and should be located in a region of shared memory

Allocating that memory and putting the semaphore there is your responsibility. This is not something that the system will do for you.

Art
  • 19,807
  • 1
  • 34
  • 60
0

the semaphore needs to be in some shared memory, not in the file global area.

Therefore need to use: shm_open() or shm_get() or mmap() to have some shared memory.

The data passed to the child process is set as 'copyonwrite' so when the child process calls the function: sem_post(), the data is copied,

As I said, the program needs some shared memory and the semaphore needs to be located within that shared memory.

user3629249
  • 16,402
  • 1
  • 16
  • 17