Take the 2-minute tour ×

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);

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


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

1 Answer 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.

share|improve this answer
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
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 8:14

Your Answer


