title: C: Signal handling and semaphores
body: <p>I'm trying to better understand semaphores and all that jazz and for that I'm programming a server and clients that communicate using shared memory and semaphores. It works pretty well and everything, but I'm not sure I understand how signal handling properly works in this case. This is some sample code from my server. I realize it may be a bit redundant to check both, but I kinda would like to understand the weird behaviour I'm experiencing:</p>
  
  <pre><code>sig_atomic_t running = 1;
  
  while(running == 1) {
      if (sem_wait(server) == -1) {
          //exit and print error A
      }
      if(running == 0) {
          //exit and print error B
      }
      /* do server stuff */
  
      if (sem_post(client) == -1) {
          //exit and print error
      }
  }
  </code></pre>
  
  <p>server is the server semaphore name, client is the client semaphore name (which doesn't really matter in this case). running (which is actually global) is the variable I use in my signal handler:</p>
  
  <pre><code>static void init_signalhandler() {
      struct sigaction sa;
      sa.sa_handler = terminate;
  
      if(sigemptyset(&amp;(sa.sa_mask)) == -1) {
          bail_out(EXIT_FAILURE, "sigemptyset error");
      }
  
      if(sigaction(SIGINT, &amp;sa, NULL) == -1) {
          bail_out(EXIT_FAILURE, "sigaction1 error");
      } 
  
      if(sigaction(SIGTERM, &amp;sa, NULL) == -1) {
          bail_out(EXIT_FAILURE, "sigaction2 error");
      }
  }
  
  static void terminate(int e) {
      running = 0;
      sem_post(server);
  }
  </code></pre>
  
  <p>Where bail_out is a custom error printing/exiting function.</p>
  
  <p>Basically no matter what I do, whenever I start up the server, it gets to the <code>sem_wait(server)</code> part. If I try to kill it by sending SIGINT, sometimes, it prints error A, and other times, it prints error B. This appears to be completely random. It kinda forces me to use the running variable though, since sometimes, the semaphore gets passed, while at other times, it does not.</p>