title: How to terminate a program using SIGALRM
body: <p>So basically I have 4-5 functions in my program. It is a lot of lines of codes and reading and writing from a file and it could end in an infinite loop (worse case) and I would like to terminate my program if it goes beyond lets say 20 seconds. below code is not working, my program hangs and the OS terminates it for me instead of the program terminating itself. I think the main problem I am having is the alarm is set in the main and when the alarm time limit is reached the process is executing in another function and this is causing the program to shut without closing files and killing child processes. This is what I have for now:</p>
  
  <pre><code>volatile sig_atomic_t keep_going = 1;
  
  /* The signal handler just clears the flag and re-enables itself. */
  void
  catch_alarm (int sig)
  {
      printf("Alarm went off");
    exit(EXIT_SUCCESS);
  }
  void function1
  {}
  void forkingfunction()
  {
  or(i=0;i&lt;size;i++,temp++)
          {
  
               pid_t pID = vfork();
  
                 if (pID == 0)                // child
                 { 
                     printf("\nchild pid %d\n",getpid());
                      //open some files and read and write
                       function1();
                        exit(EXIT_SUCCESS);
                         kill(pID,SIGKILL);
                         }
                 }
                 else if (pID &lt; 0)            // failed to fork
                 {
                     perror("Failed to fork:");
                 }
  }
  void function2
  {
  function1();
  }
  int main()
  {
  int options
  while(options){
  switch (options)
  {
  case 1:
  case 2:
  }
  }
  signal (SIGALRM, catch_alarm);
  
            alarm (0.1);//testing for 0.1 seconds 
  function1();
  
  return 0;
  }
  </code></pre>