1

I tried to synchronize tow process (child & parent) with semaphore, but my try is failed.

The C source code is the following:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <semaphore.h>
#include <fcntl.h>
#include <sys/stat.h>


int compteur=0;
sem_t *sem;

int main()
{
        void *ret;
        sem = sem_open("/sem", O_CREAT, 0644, compteur);
        sem_init(sem, 0, 0);
        pid_t pid;
        pid=fork();
        switch (pid)
        {
            case -1:
                printf("Erreur: echec du fork()\n");
                exit(1);
                break;
            case 0:
                /* PROCESSUS FILS */
                printf("Processus fils : pid = %d\n", getpid() );
                sem_post(sem);
                break;
            default:
                sem_wait(sem);
                /* PROCESSUS PERE */
                printf("Ici le pere%d: le fils a un pid=%d\n",getpid(),pid);
                printf("Fin du pere.\n");
    }   
}

I think that the problem is that the semaphore isn't visible in the child process. How can I solve this problem?

Kallel Omar
  • 1,208
  • 2
  • 17
  • 51
  • Possible duplicate, but see [here](http://stackoverflow.com/questions/6847973/do-forked-child-processes-use-the-same-semaphore) first. – bash.d Apr 16 '13 at 11:23
  • Probably you have resolved, but the solution here is to use sharedmemory for sharing the semaphore: when you create a child process, the variables oh the father are DUPLICATED, not shared (like in thread), so you are calling sem_post and sem_wait on DIFFERENT SEMAPHORES! Otherwise, if you use a segment of sharedmemory to save the semaphore and use it in different processes. I link you a program that runs good: [link](https://dl.dropboxusercontent.com/u/6701675/informatica/processi_esame.c) – Lorenzo Barbagli Jun 20 '13 at 12:19

2 Answers2

0

Your sem_init should be:

sem_init(sem, 1, 0);  

That is, second argument should be non-zero.
Because for:

#include <semaphore.h>
int sem_init(sem_t *sem, int pshared, unsigned int value);

(from man sem_init)

If  pshared  has  the  value 0, then the semaphore is shared between the threads of a process...
If pshared is nonzero, then the semaphore is shared between processes...
mohit
  • 5,696
  • 3
  • 24
  • 37
-1

0 is main process, -1 is error, any value bigger than 0 is the child. You must chance a switch to >0 to get the child.

Alper
  • 487
  • 4
  • 17
  • But when i execute it without semaphore the part "default"(>0) starts before the part (=0) in addition the dislaying of pid confirms this. – Kallel Omar Apr 16 '13 at 13:30