C信号处理程序被所有子进程激活
我需要某种signal_handler,当按下CTRL + C时,程序暂停所有操作并询问用户:«你确定要终止(Y / N)吗?»如果答案是y,程序终止,如果这是程序继续/升级它的function,这是我到目前为止所拥有的:
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); }
这段代码的问题是“你确定要终止(Y / N)吗?”消息出现的时间超过一次,我想这是因为当按下CTRL + C时程序的所有子进程都激活了这个signal_handler 。 有解决方案?