title: Unnamed semaphore POSIX IPC
body: <p>I allocated a shared memory segment of the size of an integer.</p>
  
  <p>The expected outcome on stdout should be:</p>
  
  <pre><code>P: 1
  C: 2
  </code></pre>
  
  <p>But instead it is:</p>
  
  <pre><code>C: 1
  P: 2
  </code></pre>
  
  <p>Why is the child process not being blocked until parent is done and has unlocked the shared memory segment?</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;sys/ipc.h&gt;
  #include &lt;sys/shm.h&gt;
  #include &lt;sys/wait.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;semaphore.h&gt;
  
  #define SHMSEGSIZE sizeof(int)
  
  int main(void){
  
     pid_t pid;
     int shmID;
     int *shared_mem;
  
     /* initializing shared memory */
     shmID  = shmget(IPC_PRIVATE, SHMSEGSIZE, IPC_CREAT | 0644);
     shared_mem  = (int *)shmat(shmID, 0, 0);
     *shared_mem = 0;
  
     /* initializing semaphore */
     sem_t sem;
     int pshared = 1; // !=0 for processes, =0 for threads
     int value = 1; // number of processes at a time
     sem_init(&amp;sem, pshared, value); // initialize the semaphore
  
     pid = fork();
  
     if(pid&gt;(pid_t)0){ // parent
         sem_wait(&amp;sem);
         sleep(6);
         *shared_mem += 1;
         printf("P: %d\n", *shared_mem);
         sem_post(&amp;sem);
         exit(EXIT_SUCCESS);
     } // parent
  
     if(pid==(pid_t)0){ // child
         sleep(3);
         sem_wait(&amp;sem);
         *shared_mem += 1;
         sem_post(&amp;sem);
         printf("C: %d\n", *shared_mem);
         exit(EXIT_SUCCESS);
     } // child
  
     /* fork() failed */
     printf("Failed to fork().");
     exit(EXIT_FAILURE);
  }
  </code></pre>
  
  <p>Compiled with:</p>
  
  <pre><code>gcc -o executable sem.c -pthread
  </code></pre>