Signal Handling in C

By : Dave
Source: Stackoverflow.com
Question!

How can I implement signal Handling for Ctrl-C and Ctrl-D in C....So If Ctrl-C is pressed then the program will ignore and try to get the input from the user again...If Ctrl-D is pressed then the program will terminate...

My program follows:

int main(){
 char msg[400];

 while(1){
   printf("Enter: ");
   fgets(msg,400,stdin);
   printf("%s\n",msg); 
 }
}

Thanks,

Dave

By : Dave


Answers
#include<signal.h>
#include<unistd.h>
#include<stdio.h>
void signal_catch()
{
    printf("hi,Your signal catched Here");  
}
int main()
{
    signal(SIGINT,signal_catch);
//press ctrl+c
    sleep(10);
    return 0;
}//end main

//if you want to simply ignore ctrl+c interrupt use following code in main

int main()
{
    signal(SIGINT,SIG_IGN);
    sleep(100);
    return 0;
}//end main  
//this program  wont accept ctrl+c interrupt for 100 seconds. 
By : Sherlock


This is a program for handling signal when pressed Ctrl+c

The syntax for signal function is : signal(signal name, function name);

#include<stdio.h>
#include<signal.h>  // for handling signal 

void signal_handler() 
{
    printf("Signal Handled here\n");
}

main() 
{
    printf("In main function..\n");

    // SIGINT is signal name create  when Ctrl+c will pressed 
    signal(SIGINT,signal_handler);  

    sleep(15);

    printf("In main after called from signal_handle \n");

}


In your example it seems you don't need CTRL-C handlind at all. A "signal(SIGINT,SIG_IGN)" seems enough for you, unless your application must handle a SIGINT coming from some other source. CTRL-D doesn't usually generates signals, it simply communicates the EOF condition. You can in general control the behavior of your terminal (we are talking about console input, it isn't?) by using the termios library (also here). You can enable, redefine or disable the "interrupt" character (CTRL-C), the EOF one and many other ones (XON, XOFF, modem control...)

Regards



This video can help you solving your question :)
By: admin