1

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);
  }
Gray
  • 115,027
  • 24
  • 293
  • 354
Daniel
  • 1,484
  • 5
  • 24
  • 42

1 Answers1

1

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.

Community
  • 1
  • 1
bash.d
  • 13,029
  • 3
  • 29
  • 42
  • Thanks, I came across the above code snippet while learning synchronization, and were doubting if it would work. Thanks for confirming this, and it feels great to learn new thing – Daniel Mar 21 '13 at 21:15
  • 2
    Don't forget that with named semaphores they persist beyond the lifetime of your program unless it is explicitly unlinked (or deleted on the command line). Otherwise that can cause real hell when you next run your program because the semaphore is still there at what ever value it was left with when the program last quit. – bazza Mar 22 '13 at 08:14