gpt4 book ai didi

c - 间隔定时器出现问题

转载 作者:行者123 更新时间:2023-11-30 14:28:46 25 4
gpt4 key购买 nike

我们当前的项目基于通过包含滚动来扩展更多。为此,必须将计时器间隔设置为特定时间段。我不确定的部分是报警信号的回路应该在哪里。我见过的所有示例在主函数中都有计时器值,然后在无限 while 循环中通过 pause() 显式调用信号处理程序。

我的代码有点不同,因为功能要求是这样的

print first screen of text after getting terminal dimensions
print prompt
if prompt = space, print another screen of text //WORKS
if prompe = q, restore original terminal settings & quit program //WORKS
if prompt = ENTER, initialize scroll at 1 line every 2 seconds //DOESN'T WORK
if prompt == f/s, increase/decrease scroll speed by 20% //DOESN'T WORK

读入缓冲区、文件指针和 itimerval 结构都是全局变量,以避免通过函数链作为参数传递。

该程序的主要功能是

void processInput(FILE *fp){
void printLine(int); //prints a single line of text
signal(SIGPROF, printLine);
int c;

//print first screen of text, check for more text to display

info(); //print prompt at bottom of screen
FILE *fterm= fopen("/dev/tty", "r");

while ((c=getc(fterm)) != EOF){
if (c== '\n'){
setTimer(2);

//four more conditionals like this in basic similarity

}
}

我的 setTimer 函数的基本间隔为 2 秒,并根据用户输入的 f/s 输入改变正/负 20%。

void setTimer(int direction){
int speed=2000000; //2 seconds
int change= 400000; //400 milliseconds, 20% of 2 seconds
if (direction == 1) //slow down by 20%
speed+= change;
if (direction == 0)
speed -= change;

timer.it_value.tv_sec=2;
timer.it_value.tv_usec=0;
timer.it_interval.tv_sec=0;
timer.it_interval.tv_usec= speed;

setitimer(ITIMER_PROF, &timer, NULL);

}

第一个问题:我应该使用 SIGALRM 还是 SIGPROF,并相应地更改 ITIMER_XXXX 变量?

第二,我应该在哪里放置循环来触发信号?我试过了

while(1)
pause();

在几个条件中,但它具有停止执行并忽略任何输入的效果。

最佳答案

在不知道您的要求的详细信息的情况下,您是否可以使用更轻松地做到这一点 select()

将初始选择超时设置为 2 秒,并根据 f/s 输入进行调整,同时如果超时之前有任何标准输入,则进行处理。

或多或少有效的概要:

   int retval;
fd_set rfds;

int input = fileno(fterm);

struct timeval tv, delay;

delay.tv_sec = 2;
delay.tv_usec = 0;

while (true)
{
FD_ZERO(&rfds);
FD_SET(input, &rfds);

tv.tv_sec = delay.tv_sec;
tv.tv_usec = delay.tv_usec;

retval = select(input + 1, &rfds, NULL, NULL, &tv);

if (retval == -1)
perror("select()");
else
if (retval)
{
if (FD_ISSET(input, &rfds))
{
command = readInput(...);

switch(command)
{
case 'q' ... cleanup & quit
case 's' ... calc 20% off delay values
case etc ...
case default...error handling
}
}
}
else //timeout
printLine();
}

关于c - 间隔定时器出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5602289/

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