C signal handler getting activated by all child processes

本秂侑毒 提交于 2020-01-25 21:27:28

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!