title: Simple Linux Signal Handling
body: <p>I have a program that creates many threads and runs until either power is shutdown to the embedded computer, or the user uses <code>kill</code> or <kbd>ctrl</kbd><kbd>c</kbd> to terminate the process.</p>
  
  <p>Here's some code and how the main() looks.</p>
  
  <pre><code>static int terminate = 0;  // does this need to be volatile?
  
  static void sighandler(int signum) { terminate = 1; }
  
  int main() {
    signal(SIGINT, sighandler);
    // ...
    // create objects, spawn threads + allocate dynamic memory
    // ...
    while (!terminate) sleep(2);
    // ...
    // clean up memory, close threads, etc.
    // ...
    signal(SIGINT, SIG_DFL);  // is this necessary?
  }
  </code></pre>
  
  <p>I'm wondering a few things:</p>
  
  <ol>
  <li><p>Is any signal handling necessary?<br>
  I read in this thread <a href="https://stackoverflow.com/questions/7376228/linux-c-catching-kill-signal-for-graceful-termination">"Linux C catching kill signal for graceful termination"</a>, that apparently the OS will handle cleanup for me. 
  Therefore, can I just replace the signal handler with just an infinite loop and let the OS gracefully exit the threads, de-allocate the memory, etc?   </p></li>
  <li><p>Are there any other signals that I need to be concerned with regarding clean termination?  This thread <a href="https://stackoverflow.com/questions/4042201/how-does-sigint-relate-to-the-other-termination-signals">"How does SIGINT relate to the other termination signals?"</a>, was useful to list all the signals I may be concerned with, but how many actually required handling?</p></li>
  <li><p>Does the terminate variable in my example have to be volatile?  I've seen many examples where this variable is volatile, and others where it is not.</p></li>
  <li><p>I've read that <code>signal()</code> is now deprecated, and to use <code>sigaction()</code>. Are there any really good examples to show how to convert from the previous <code>signal()</code> call?  I'm having trouble with the new structure that I have to create/pass and how it all fits together.</p></li>
  <li><p>Is the second call to <code>signal()</code> necessary?<br>
  Is there something similar that I need to be concerned with for <code>sigaction()</code>?</p></li>
  </ol>
  
  <p>To be clear, all I'm trying to accomplish to to have my: main loop run until either <kbd>ctrl</kbd><kbd>c</kbd> or power is disconnected or something really bad happens.</p>