James wrote:
> is it possible to have a function called when the user presses ^C or kills
> the program so that the program can 'clean up' before being terminated? (i.e
> close all open files, write out data, free allocated memory etc). if so, how?
Use sigaction() to install a handler for SIGINT, e.g.
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
...
static void sigint_handler(int signum)
{
/* code to perform clean up */
exit(0);
}
static int install_handler(void)
{
struct sigaction act;
act.sa_handler = sigint_handler;
sigemptyset(&act.sa_mask);
act.sa_flags = SA_ONESHOT;
if (sigaction(SIGINT, &act, NULL) != 0)
{
perror("install_handler: sigaction");
return -1;
}
return 0;
}
NB: Not all functions can safely be called from within a signal
handler. Stevens[1] gives a list of those which can in Fig 10.3.
According to POSIX, this doesn't include exit(), but the SVR4 SVID
allows this. AFAICT, Linux does too.
If you want to call functions which aren't re-entrant (this may
include much of the stdio library, as well as malloc and free), you'll
need to do so from outside the signal handler, e.g. by setting a flag
within the signal handler, and having the program's main loop
terminate when the flag is set (don't forget to declare the flag
variable as `volatile').
--
Glynn Clements <[EMAIL PROTECTED]>
[1]
Advanced Programming in the Unix(R) Environment
W Richard Stevens
Addison Wesley, 1992
ISBN: 0-201-56317-7