title: how to detect Linux shutdown/reboot
body: <p>I'm trying to detect shut down or reboot from Linux in my c program.
  I found that program can use signal(SIGTERM, handler) (SIGKILL, handler).
  But these two will trigger if user kill the process with command, too.</p>
  
  <p>At some solutions, they said can use runlevel but it won't work.
  Don't know if the process is kill before the system init the runlevel.
  I even try to put script in rcx.d, but it still won't work.</p>
  
  <p>Does anyone has some advise?
  I need to run on many kinds of Linux system.</p>
  
  <p>Thanks.</p>
  
  <p>[Update]
  I use R solution, but I still don't see my data were clear at reboot or shutdown.
  Is it my function is wrong??</p>
  
  <pre><code>int start() {
      if (initIni() == EXIT_FAILURE)
          return EXIT_FAILURE;
      struct sigaction act;
      memset(&amp;act, '\0', sizeof(act));
      act.sa_sigaction = &amp;signal_callback_handler;
      act.sa_flags = SA_SIGINFO;
      sigaction(SIGTERM, &amp;act, NULL);
  ....
  }
  
  void signal_callback_handler(int signum, siginfo_t *siginfo, void *context) {
      if (signum == SIGTERM &amp;&amp; (long)siginfo-&gt;si_pid == 1) {
          clearData();
      }
      exit(signum);
  }
  </code></pre>
  
  <p>[Update]
  Finally, I use David Schwartz runlevel(8) <a href="http://code.metager.de/source/xref/gnu/sysvinit/src/runlevel.c" rel="noreferrer">example</a> to solve my problem.
  It won't be useful if you use linux command runlevel.
  Thanks for the great solution. </p>