title: Understanding the posix interprocess semaphore
body: <p>According to my understanding, a semaphore should be usable across related processes without it being placed in shared memory. If so, why does the following code deadlock?</p>
  
  <pre class="lang-c prettyprint-override"><code>#include &lt;iostream&gt;
  #include &lt;semaphore.h&gt;
  #include &lt;sys/wait.h&gt;
  
  using namespace std;
  
  static int MAX = 100;
  
  int main(int argc, char* argv[]) {
    int retval;
    sem_t mutex;
  
    cout &lt;&lt; sem_init(&amp;mutex, 1, 0) &lt;&lt; endl;
  
    pid_t pid = fork();
  
    if (0 == pid) {
      //     sem_wait(&amp;mutex);
      cout &lt;&lt; endl;
      for (int i = 0; i &lt; MAX; i++) {
        cout &lt;&lt; i &lt;&lt; ",";
      }
      cout &lt;&lt; endl;
      sem_post(&amp;mutex);
  
    } else if(pid &gt; 0) {
      sem_wait(&amp;mutex);
      cout &lt;&lt; endl;
      for (int i = 0; i &lt; MAX; i++) {
        cout &lt;&lt; i &lt;&lt; ",";
      }
      cout &lt;&lt; endl;
      //     sem_post(&amp;mutex);
      wait(&amp;retval);
  
    } else {
      cerr &lt;&lt; "fork error" &lt;&lt; endl;
      return 1;
    }
  
  //   sem_destroy(&amp;mutex);
  
    return 0;
  }
  </code></pre>
  
  <p>When I run this on Gentoo/Ubuntu Linux, the parent hangs. Apparently, it did not receive the post by child. Uncommenting sem_destroy won't do any good. Am I missing something?</p>
  
  <p><strong>Update 1:</strong>
  This code works</p>
  
  <pre><code>mutex = (sem_t *) mmap(NULL, sizeof(sem_t), PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED, 0, 0);
  if (!mutex) {
    perror("out of memory\n");
    exit(1);
  }
  </code></pre>
  
  <p>Thanks,
  Nilesh.</p>