[英]linux: alarm function doesn't work sometimes?
我的代碼如下,第一次,警報工作得很好,並且handler2()函數可以工作。 但是,在“ handler2()”中實現“ doMain()”后,該警報不起作用。
我的意思是在第二次打印“”在主Pleasae輸入中:\\ n“”之后,handler2()不再起作用。
不知道為什么 我的代碼如下:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <setjmp.h>
#define MAX_LEN_COMM 64
jmp_buf jumper;
int stop =0; //o is not stop ,otherwise is stop;
void hanlder2();
void doMain();
void handler2()
{
int len_command = 0;
char character;
char commandStr[60];
printf("******************************\n");
printf("In Alarm Pleasae input: \n");
while((character=getchar())!='\n')
{
commandStr[len_command]=character;
len_command++;
}
commandStr[len_command]='\0';
printf("In Alarm input is %s\n",commandStr);
if (strcmp(commandStr,"N")==0||strcmp(commandStr,"n")==0){
printf("In Alarm You put no, we will stop alarm \n");
stop=1;
longjmp(jumper, 2);
}
else if(strcmp(commandStr,"Y")==0||strcmp(commandStr,"y")==0){
printf("In Alarm You put yes, we will continue alarm \n");
signal(SIGALRM, handler2);
alarm(5);
doMain();
}
}
void doMain(){
while(1){
setjmp(jumper);
if(stop==0){
signal(SIGALRM, handler2);
printf("return time %d\n",alarm(5));
}
int len_command = 0;
char character;
char commandStr[60];
printf("In main Pleasae input: \n");
while((character=getchar())!='\n')
{
commandStr[len_command]=character;
len_command++;
}
commandStr[len_command]='\0';
printf("In main input is %s\n",commandStr);
if (strcmp(commandStr,"N")==0||strcmp(commandStr,"n")==0){
printf("In main You put no\n");
}
else if(strcmp(commandStr,"Y")==0||strcmp(commandStr,"y")==0){
printf("In main You put yes\n");
}
}
}
void main()
{
doMain();
}
你在做什么是非常錯誤的。
首先,處理程序的簽名應為void handler(int sig)
。
其次,在處理程序中可以安全使用的功能很少,因此您應嘗試盡快退出處理程序,並且絕對不要執行控制台I / O。 您正在使用幾個不安全的庫函數。
最后,信號處理程序是一個函數。 它運行並返回到您的程序被信號中斷的位置。 在這段時間內,處理程序運行的同一類型的信號不會傳遞。 通過從處理程序調用doMain()
-這很瘋狂-處理程序永無止境。 因為它還沒有結束,所以您將不會再看到任何警報信號。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.