How to write a C Program to show how a signal handler works in C Programming Language ?
Solution:
/* This C Program shows how a signal handler works.
- run this and press Ctrl-C a few times */
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
char rudone();
main()
{
void f(int); /* declare the handler */
int i;
signal( SIGINT, f ); /* install the handler */
for(i=0; i<5; i++ ){ /* do something else */
printf("hello\n");
sleep(1);
}
}
void f(int signum) /* this function is called */
{
char input;
printf("Interrupted! OK to quit(y/n)?");
input = done();
if(input == 'y'){
exit(0);
}
}
char rudone(){
char* yesno;
scanf("%c", &yesno);
if(yesno[0] == '\0'){
printf("No input entered: OK to quit(y/n)?");
done();
}
return yesno[0];
}