title: Correct cleaning at signal handler function
body: <p>I have made a program which uses the <code>fork()</code> function in order to make child processes. Its child processes do some work, but I want them to terminate when they receive a <code>SIGTERM</code> signal from the parent process. Before exiting, I also want them to clean up arrays that I have allocated and send some stuff through FIFOs to the parent process. So I have 2 scenarios. </p>
  
  <ol>
  <li><p>Global variables for my arrays as well as file descriptors for the FIFOs and then exit through the signal handler function, for example:</p>
  
  <pre><code>/*global variables*/
  struct whatever ** test;
  int test_size;
  int fd_in, fd_out;
  
  /*handler*/
  void shutdown(int signo)
  {
        /*free memory for the arrays malloc'd through the program*/
        /*send message with the help of fd_out*/
        /*close fd_in and fd_out*/
        _exit(0);
  }
  </code></pre></li>
  <li><p>Declare a global int flag and when the child processes perceive that the flag has changed, they then clean up the arrays, send messages and exit.</p>
  
  <pre><code>/*global variables*/
  int exit_flag=0;
  
  /*handler*/
  void shutdown(int signo)
  {
        exit_flag=1;
  }
  
  /*child process*/
  int main()
  {
        /*declare fds and arrays*/
        /*use sigaction and set up handler*/
  
        while(!exit_flag)
        {
               /*do stuff*/
        }
  
        /*free memory*/
        /*send message with the help of fd_out*/
        /*close fds*/
  }
  </code></pre></li>
  </ol>
  
  <p>My question is which scenario leads to good coding/programming? Are they both the same or there is a better and even more correct way to do this?</p>