title: Working with semaphores and shared memory under Linux
body: <p>I need to write a program that is creating a N amount of sub processes and every single one of them adds one to a shared memory variable. My idea is to use semaphores and shared memory, but the processes are not waiting for each other and the shared memory variable is also not working as I want it.</p>
  
  <p><strong>mydefs.h</strong></p>
  
  <pre><code>#ifndef __MYDEFS__H__
  #define __MYDEFS__H__
  // Includes
  #include &lt;stdio.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;semaphore.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;signal.h&gt;
  #include &lt;errno.h&gt;
  #include &lt;memory.h&gt;
  #include &lt;sys/ipc.h&gt;
  #include &lt;sys/msg.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;sys/shm.h&gt;
  #endif // __MYDEFS__H__
  </code></pre>
  
  <p><strong>main.c</strong></p>
  
  <pre><code>#include "mydefs.h"
  #define PROC_COUNT 3
  #define INITAL_MARKER_VALUE 0
  #define PID_LEN 32
  
  char mypid[PID_LEN];
  
  int main()
  {
      int i, shm_id;
      sem_t mutex;
      if(sem_init(&amp;mutex,1,1) &lt; 0)
      {
          perror("semaphore initilization");
          exit(0);
      }
      shm_id = shmget(IPC_PRIVATE, 4*sizeof(int), IPC_CREAT | 0666);
      if (shm_id &lt; 0) {
           printf("shmget error\n");
      }
      int *shmpointer = shmat(shm_id,0,0);
      memset(mypid, 0, sizeof(mypid));
      sprintf(mypid, "%06d", getpid());
  
      for(i = 0; i &lt; PROC_COUNT; i++)
      {
          if (fork() == 0)
          {
              while(sem_wait(&amp;mutex)!=0);
              execl("slaveproc", "slaveproc", mypid, (char *)0);
              shmpointer += 1;
              sem_post(&amp;mutex);
              perror("\n Can't exec slave program. Cause ");
              exit(1);
          }
      }
      sleep(1);
      printf("%d\n", *shmpointer);
      return 0;
  }
  </code></pre>
  
  <p><strong>slaveproc.c</strong></p>
  
  <pre><code>#include "mydefs.h"
  
  int marker; // Marker value
  
  int main(int argc, char *argv[])
  {
      master_pid = atoi(argv[1]);
      printf("\n --------------------------------------");
      printf("\n I'm the slave proc!");
      printf("\n My pid: %d", getpid());
      printf("\n My master's pid: %d", master_pid);
      printf("\n --------------------------------------");
      for(;;) pause();
          return 0;
  }
  </code></pre>