gpt4 book ai didi

linux:闹钟功能有时不起作用?

转载 作者:太空宇宙 更新时间:2023-11-04 03:52:06 25 4
gpt4 key购买 nike

我的代码如下,第一次,alarm工作得很好,handler2()函数也可以工作。但是,在“handler2()”中实现“doMain()”后,闹钟就不起作用了。

我的意思是在第二次打印“”In main Pleasae input:\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() - 这很疯狂 - 处理程序永远不会结束。因为它不会结束,所以您不会再看到任何警报信号。

关于linux:闹钟功能有时不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26028401/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com