title: Why semop() hangs?
body: <p>When trying run this code: At first it prints "Process <code>some_id</code> BEFORE enter" for each semaphor (2 times). Then it hangs. What is incorrect?</p>
  
  <pre><code># include &lt;sys/ipc.h&gt;
  # include &lt;sys/sem.h&gt;
  # include &lt;unistd.h&gt;
  # include &lt;errno.h&gt;
  # include &lt;stdio.h&gt;
  # include &lt;stdlib.h&gt;
  # include &lt;iostream&gt;
  
  int seminit()
  {
      key_t key = ftok("/bin", 1);
      int semid = semget (key, 1, IPC_CREAT | IPC_EXCL | 600);
      if(-1 == semid)
          if(EEXIST == errno)
              semid = semget(key, 1, 0);
      return semid;
  }
  
  void uninit(int semid)
  {
          semctl(semid, 0, IPC_RMID);
  }
  
  void semlock(int semid)
  {
      struct sembuf p_buf;
      p_buf.sem_num = 0;
      p_buf.sem_op = -1;
      p_buf.sem_flg = SEM_UNDO;
      if(semop(semid, &amp;p_buf, 1) == -1)
          printf("semlock failed: ERRNO: %d\n", errno);
  }
  void semunlock(int semid)
  {
      struct sembuf v_buf;
      v_buf.sem_num = 0;
      v_buf.sem_op = 1;
      v_buf.sem_flg = SEM_UNDO;
      if(semop(semid, &amp;v_buf, 1) == -1)
          printf("semunlock failed: ERRNO: %d\n", errno);
  }
  void some_function()
  {
      int semid = seminit();
      pid_t pid = getpid();
      printf("Process %d BEFORE enter\n", pid);
      semlock(semid);
      printf("Process %d IN Critical section\n", pid);
      sleep(10);
      semunlock(semid);
      printf("Process %d AFTER leave\n", pid);
      uninit(semid);
  }
  
  int main(int argc, char** argv) 
  {
      for(int i = 0; i &lt; 2; ++i)
          if(0 == fork())
              some_function();
      return (EXIT_SUCCESS);
  }
  </code></pre>