This is from the tutorial:
Code:
#include <ctype.h>
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
char *prog; /* program name -- always in argv[0] */
char temp_filename[20]; /* template for a temporary file */
/** Function to act as an interrupt handler. */
int handle_ctl_c()
{
fprintf(stderr, "%s: handle_ctl_c: caught interrupt signal.\n",prog);
fprintf(stderr, "%s: handle_ctl_c: remove temporary file %s\n",prog, temp_filename);
unlink(temp_filename);
exit(0);
}
int main(int argc, char *argv[])
{
FILE *file_p; /* file pointer for temporary file */
prog = argv[0]; /* program name for diagnostic output */
/* create temporary file */
sprintf(temp_filename, "tmp%d", getpid());
file_p = fopen(temp_filename, "w");
fprintf(file_p, "Temporary file generated by process %d.\n",getpid());
fclose(file_p);
fprintf(stderr, "%s: created temporary file %s\n",prog, temp_filename);
/** Ignore interrupt signal (SIGINT) for 5 seconds. */
signal(SIGINT, SIG_IGN);
fprintf(stderr, "%s: SIGINT is now ignored.\n", prog);
fprintf(stderr, "%s: ctl-c is now ineffective.\n", prog);
sleep(5);
/** handle_ctl_c will be called when a SIGINT is received. */
signal(SIGINT, (SignalHandler) handle_ctl_c);
fprintf(stderr, "%s: handle_ctl_c is now the SIGINT signal handler.\n",prog);
sleep(5);
/** SIGINT will now interrupt the program. */
signal(SIGINT, SIG_DFL);
fprintf(stderr, "%s: SIGINT now has the default handler.\n", prog);
sleep(5);
/** remove the temporary file created earlier. */
fprintf(stderr, "%s: remove temporary file %s\n",prog, temp_filename);
unlink(temp_filename);
exit(0);
}