title: How to use mutexes in a shared memory forked process?
body: <p>I'm sharing a counter variable between a multi-process program, where processes are created using the fork() call. I'm using the following code to create a shared memory where the counter is stored, and can be accessed and incremented by each process.</p>
  
  <p>This is the thread creation mechanism in the main parent thread</p>
  
  <pre><code>void createSHM()
  {
  int key = SHMKEY;
  int *shm;
  
  if ((shmid = shmget(key, SHMSZ, IPC_CREAT | 0666)) &lt; 0) {
      perror("shmget");
      exit(1);
  }
  
  if ((shm = shmat(shmid, NULL, 0)) == (char *) -1) {
      perror("shmat");
      exit(1);
  }
  *shm=0
  }
  </code></pre>
  
  <p>and this is the function called in each of the forked processes to get the value of the counter, and increment it.</p>
  
  <pre><code>int attachSHMandIncrement()
  {
  int key = SHMKEY;
  int *shm;
  
  if ((shmid = shmget(key, SHMSZ, 0666)) &lt; 0) {
      perror("shmget");
      exit(1);
  }
  
  if ((shm = shmat(shmid, NULL, 0)) == (char *) -1) {
      perror("shmat");
      exit(1);
  }
  *shm++;
  return *shm;
  }
  </code></pre>
  
  <ol>
  <li><p>I'm not sure if this implementation is race free? Can anyone comment on if it is, and if not, an example of how this can be made race free?</p></li>
  <li><p>Given the fact that these are forked processes and will inherit the memory at the time of fork. Is there anything I should keep in mind? I've done this before in totally separate processes but here I might have to do it in forked processes.</p></li>
  </ol>