帮助解决设置计时器/信号问题
我有以下代码,我希望它会等待 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 秒。
有什么想法吗?
谢谢 M。
I have the following code which I'd hope would wait 2 seconds then wait 5 seconds in a loop.
There is a reason why I'm not using the it_interval to refire the timer.
#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 );
}
}
It produces the following output
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
I can't work out why it isn't waiting for the 5 seconds for the second timer.
Any ideas?
Thx
M.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
啊哈!修好了。
sem_wait
被中断并返回-1
和errno == EINTR
所以我必须有这样的东西。Aha! fixed it.
the
sem_wait
was being interrupted and returning-1
anderrno == EINTR
so I have to have something like this.