title: How to properly remove semaphores after usage?
body: <p>I'm using a large number of semaphores to synchronize multi-process access to shared memory.</p>
  <p>I initialize the semaphores via</p>
  <pre><code>int scount = 80000;
  int semid = semget(IPC_PRIVATE, scount, 0666 | IPC_CREAT);
  </code></pre>
  <p>which works fine.</p>
  <p>At the end of the program I remove the semaphore set via</p>
  <pre><code>semctl(semid, 0, IPC_RMID);
  </code></pre>
  <p>However, when I check the number of semaphores in the system via</p>
  <pre><code>ipcs -S 
  </code></pre>
  <p>in the console, I see they are still there.</p>
  <pre><code>seminfo:
      semmap:     30  (# of entries in semaphore map)
      semmni:      8  (# of semaphore identifiers)
      semmns:  80064  (# of semaphores in system)       &lt;------ ????
      semmnu:      0  (# of undo structures in system)
      semmsl:  87381  (max # of semaphores per id)
      semopm:      5  (max # of operations per semop call)
      semume:     10  (max # of undo entries per process)
      semusz:     32  (size in bytes of undo structure)
      semvmx:  32767  (semaphore maximum value)
      semaem:  16384  (adjust on exit max value)
  </code></pre>
  <p>I also tried to remove them manually in the console via</p>
  <pre><code>ipcrm -s [semid]
  </code></pre>
  <p>which seems to remove the set fine (i.e. the <code>semid</code> is listed in <code>ipcs -s</code> before the command and gone after). Yet <code>ipcs -S</code> still shows the</p>
  <pre><code>semmns:  80064  (# of semaphores in system)
  </code></pre>
  <p>How do I properly cleanup the semaphores after usage, so they do <strong>not</strong> show up in <code>&quot;semmns:  .... (# of semaphores in system)&quot;</code> anymore?</p>
  <p>The reason I'm asking is that if the semaphores are not properly cleaned up, my next run of the program won't work because the number of open semaphores will exceed the limit. I need to restart to reset it to 0.</p>
  <p>PS: I'm on Mac OS, but would also want it to work on Linux.</p>
  <hr />
  <p><code>semget</code> does not return an error. The error occurs at the next step when I initialize the semaphore set via:</p>
  <pre><code>semun_t semun = {.val = 1}; // initial semaphore value =&gt; 1 = released
  for (int i=0; i&lt;scount; i++){
          if(semctl(semid, i, SETVAL, semun) == -1) {perror(&quot;semctl init&quot;);exit(1);}
      }
  </code></pre>
  <p>The error I get there is:</p>
  <pre><code>semctl init: Invalid argument
  </code></pre>