【发布时间】:2013-03-13 07:02:59
【问题描述】:
我这样的程序信号处理程序?
sig_quit(int signo)
{
//char ans[5];
char ans;
printf("Are you sure want to exit program ?Y/N \n");
//while(check){ check = !scanf("%s", ans); }
//scanf("%c",&ans);
ans=getchar();
//fgets(ans,sizeof(ans),stdin);;
printf("ans is : %c",ans);
if(ans=='y' || ans=='Y')
{
printf("Goodbye\n");
exit(0);
return;
}
else if(ans!='y')
{
printf("why ans is : %c",ans);
}
}
好的默认行为是当你按下 ctrl+\
问题问你“你确定要退出”吗?
如果用户按下'y',它将退出,但如果用户按下'y'以外的任何其他内容->它将再次停留在scanf,但我需要退出该功能并在用户按下后返回主怎么样?
简而言之:它卡住@ getchar()或scanf(),在插入除'y'之外的任何字符后再次卡住,提示它进行新输入,如果用户插入任何新字符它会卡住后退出信号处理函数回到main()
这是新版本的代码:
所以这是最近的代码:
volatile sig_atomic_t eflag = 0;
int main(int argc, char *argv[])
{
/*Here are some code ,,,,,, */
Signal(SIGQUIT, sig_quit); /* must call waitpid() */
while (eflag)
{
/* Main loop program code */
log_msg(SIGQUIT);
}
////// there is code below...
.
.
.
}
void log_msg(int signum)
{
char ans;
//signal(SIGQUIT,SIG_IGN);
printf("Are you sure want to exit program ?Y/N \n");
do {
ans=getchar();
if(ans=='y' || ans=='Y')
{
printf("Goodbye\n");
exit(0);
return;
}
if(ans == 'n' || ans == 'N') return;
}while(1);
}
void
sig_quit(int signo)
{
eflag = 1;
/* Do some handling specific to SIGINT */
log_msg(SIGQUIT);
}
如果用户按下“n||N”,getchar() 仍然会再次阻塞,直到他再次按下任何 char 并返回 main()。
【问题讨论】:
-
这些函数在大多数信号处理程序中是不合法的;您正在调用 UB。
标签: c function signals printf scanf