This is an extension to a question I asked before. Override Ctrl-C
I have this code that is handling the signal for ctrl-c, while this worked on one machine, I ran it on another and it now once again exits the program after ctrl-c is pressed.
When I asked my 开发者_开发技巧professor he told me that in the handler I will need to prevent the signal from being processed further, but I am not sure how to do this.
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <signal.h>
#include "Input.h"
#include "CircleBuff.h"
sig_atomic_t sigflag = 0;
void catch_int(int sig_num) {
sigflag = 1;
//printf("to do: Print history");
}
void printHistory(CircleBuff hist) {
cout << "Complete History:\n" << endl;
hist.print();
cout << endl;
}
int main(int argc, char** argv) {
signal(SIGINT, catch_int);
//my code here
do {
//more code here
if (sigflag != 0) {
printHistory(history);
sigflag = 0;
}
} while(report != 0); //which is assigned in the code
Here is the reduced code:
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <signal.h>
sig_atomic_t sigflag = 0;
void catch_int(int sig_num) {
sigflag = 1;
printf("to do: Print history");
}
int main(int argc, char** argv) {
signal(SIGINT, catch_int);
do {
} while(1);
}
Did you try signal(SIGINT, SIG_IGN);
?
I assume that will work
Edit:
I went back and reduced your program just a bit and the handler seems to work (every invokation increases the flag), yet the actual syscall (sleep in mycase) is aborted.
Can you retest and restate what is not working for you in this reduced sample?
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
volatile sig_atomic_t ctrlCcount = 0;
void catch_int(int sig_num){
ctrlCcount++;
}
int main(int argc, char** argv){
signal(SIGINT, catch_int);
do{
sleep(5);
printf("Ctrl-C count=%d\n", ctrlCcount);
}while(1);
return 0;
}
精彩评论