问题
I need some kind of signal_handler that when pressed CTRL+C, the program pauses all it's operations and asks the user: «Are you sure you want to terminate(Y/N)?» If the answer is y, the program terminates, if it's n the program continues/prooceeds with it's functions, this is what i have till this moment:
void sig_handler(int sig){
if(sig == SIGINT){
char res;
printf("\nAre you sure you want to terminate (Y/N)?\n");
kill(0, SIGTSTP); //envia sinal Stop ao processo pai
do{
read(STDIN_FILENO, &res, 1);
if (res == 'Y' || res == 'y')
{
kill(0,SIGTERM); //envia sinal de Terminacao ao proceso pai
}else
if (res == 'N' || res == 'n')
{
kill(0,SIGCONT); //envia sinal ao processo pai para continuar
break;
}
}while(res != 'Y' && res != 'y' && res != 'N' && res != 'n');
}
}
struct sigaction oldsigaction; //declarar antes de subscribe_SIGINT
void subscribe_SIGINT(){
sigaction(SIGTSTP, 0,&oldsigaction);
struct sigaction newsigaction;
newsigaction = oldsigaction;
newsigaction.sa_handler = &sig_handler;
sigaction(SIGTSTP, &newsigaction,0);
signal(SIGINT, sig_handler);
}
The problem with this code is that the message «Are you sure you want to terminate(Y/N)?» appears more then once, i suppose that happens because all the child processes of the program activate this signal_handler when CTRL+C is pressed. Any solutions?
来源:https://stackoverflow.com/questions/43379322/c-signal-handler-getting-activated-by-all-child-processes