gpt4 book ai didi

c - 帮助解决 setitimer/信号问题

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

我有以下代码,我希望它会等待 2 秒,然后循环等待 5 秒。

我没有使用 it_interval 重新启动计时器是有原因的。

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <signal.h>
#include <time.h>
#include <sys/time.h>

#include <semaphore.h>

sem_t sem;

void sighdlr( int sig )
{
printf( "sighdlr\n" );
sem_post( &sem );
}

int main( int c, char *v[] )
{
signal( SIGALRM, sighdlr );

struct itimerval itv;
struct tm tm;
time_t now;

while( true )
{
itv.it_value.tv_sec = 2;
itv.it_value.tv_usec = 0;
itv.it_interval.tv_sec = 0;
itv.it_interval.tv_usec = 0;
setitimer( ITIMER_REAL, &itv, NULL );

sem_wait( &sem );
now = time( NULL );
localtime_r( &now, &tm );
fprintf( stderr, "%02d:%02d:%02d\n", tm.tm_hour, tm.tm_min, tm.tm_sec );

itv.it_value.tv_sec = 5;
itv.it_value.tv_usec = 0;
itv.it_interval.tv_sec = 0;
itv.it_interval.tv_usec = 0;
setitimer( ITIMER_REAL, &itv, NULL );

sem_wait( &sem );
now = time( NULL );
localtime_r( &now, &tm );
fprintf( stderr, "%02d:%02d:%02d\n", tm.tm_hour, tm.tm_min, tm.tm_sec );
}
}

它产生以下输出

sighdlr
15:32:50
15:32:50
sighdlr
15:32:52
15:32:52
sighdlr
15:32:54
15:32:54
sighdlr
15:32:56
15:32:56
sighdlr
15:32:58
15:32:58
sighdlr
15:33:00
15:33:00

我不明白为什么它不等待第二个计时器的 5 秒。

有什么想法吗?

谢谢

最佳答案

啊哈!修复它。

sem_wait 被中断并返回 -1errno == EINTR 所以我必须有这样的东西。

do {
ret = sem_wait( &sem );
} while( ret < 0 && errno == EINTR );

关于c - 帮助解决 setitimer/信号问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3624668/

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