Daniel
Daniel

Reputation: 1554

semaphore concurrency

In the following code, wouldn't a mutex be created, in the child, as a copy of its parent's? Hence there're two copies of mutexs now -- one in child, and one in parent. How can it be synchronized? As far as I can remember, you need one copy that are shared by multiple processes in order to make it synchronize.

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

  int main(int argc, char **argv)
  {
    int fd, i,count=0,nloop=10,zero=0,*ptr;
    sem_t mutex;

    //open a file and map it into memory

    fd = open("log.txt",O_RDWR|O_CREAT,S_IRWXU);
    write(fd,&zero,sizeof(int));

    ptr = mmap(NULL,sizeof(int), PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);

    close(fd);

    /* create, initialize semaphore */
    if( sem_init(&mutex,1,1) < 0)
      {
        perror("semaphore initilization");
        exit(0);
      }
    if (fork() == 0) { /* child process*/
      for (i = 0; i < nloop; i++) {
        sem_wait(&mutex);
        printf("child: %d\n", (*ptr)++);
        sem_post(&mutex);
      }
      exit(0);
    }
    /* back to parent process */
    for (i = 0; i < nloop; i++) {
      sem_wait(&mutex);
      printf("parent: %d\n", (*ptr)++);
      sem_post(&mutex);
    }
    exit(0);
  }

Upvotes: 1

Views: 804

Answers (1)

bash.d
bash.d

Reputation: 13207

You must not confuse a mutex with a semaphore. A semaphore might allow several threads/processes to access a resource, a mutex allows only ONE concurrent access to a resource.
As stated here you would need to create a named semaphore to make cross-process-synchronisation possible. You must create a semaphore in your parent process and access is using sem_open in the child process to achieve synchronisation.

Upvotes: 1

Related Questions