On Tue, 16 Jun 1998, James wrote:

> is it possible to have a function called when the user presses ^C or kills

^C generates SIGINT so u may catch it by sigaction()/signal()

SIGKILL cannot be caught so if your process is kill-ed it has no chance of
cleaning after itself. Cleanup routines registered with atexit() are not
called also.


> the program so that the program can 'clean up' before being terminated? (i.e
> close all open files, 

automatically done by the kernel when the process is terminated/exits

>write out data, 

add the necessary code to the signal handler 

>free allocated memory etc). 

automatically done by the kernel when the process is terminated/exits


>if so, how?

This ugly piece of code shows the idea...You may wish to take a look at
the Signal Handling section of the libc info files (Ctrl-H , and then I
in emacs) 

#include <stdio.h>
#include <signal.h>

struct sigaction sa;

void handle_sigint()
{
  /* your cleanup code */

  printf("Doing cleanup\n");
  fflush(stdout);
  
  raise(SIGINT);
  
  return;   
}


int main()
{  

  sa.sa_handler = handle_sigint;
  sa.sa_flags |= SA_ONESHOT;
  
  sigaction(SIGINT,&sa,NULL);
  
  printf("Press Ctrl+C...\n");
    
  return 0;
}


Hope this helps...

        Marin


 
          -= Why do we need gates in a world without fences? =-


Reply via email to