我做了一个简单的程序,我反复创建和销毁一些计时器;使用第一个计时器,程序正确运行,创建和销毁计时器;但是对于第二个计时器,当我执行timer_settime()时,我得到错误"无效的参数&#34 ;;没有定时删除,只有撤防定时器,代码运行正常;为什么这个?
这是我的代码:
#include <signal.h>
#include <time.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
int d,x = 0;
void err_exit(char* str)
{
perror(str);
exit(EXIT_FAILURE);
}
void sighandler(int sig, siginfo_t *si, void *uc)
{
(void) sig;
(void) uc;
d = si->si_value.sival_int;
++x;
}
void handle_signal(struct sigaction* sa)
{
sa->sa_flags = SA_SIGINFO;
sa->sa_sigaction = sighandler;
sigemptyset(&sa->sa_mask);
if (sigaction(SIGRTMAX,sa,NULL) == -1)
err_exit("sigaction");
}
void create_timer(struct sigevent* sev,timer_t* timer_id,int i)
{
union sigval s;
s.sival_int = i+11;
printf("value: %d\n",i);
sev->sigev_notify = SIGEV_SIGNAL;
sev->sigev_signo = SIGRTMAX;
sev->sigev_value = s;
timer_create(CLOCK_REALTIME,sev,timer_id);
}
void set_timer(timer_t timer_id,struct itimerspec* ts,int j)
{
if(ts == NULL)
printf("itimerspec null\n");
printf("creating timer %ju\n",timer_id);
if (timer_settime(timer_id, 0, ts, NULL) == -1){
printf("errno code: %d\n",errno);
err_exit("timer_settime");
}
}
void initialize_timerspec(struct itimerspec* ts)
{
ts->it_value.tv_sec = 2;
ts->it_value.tv_nsec = 5;
ts->it_interval.tv_sec = 0;
ts->it_interval.tv_nsec = 0;
}
void reset_timer(timer_t timer_id,int j)
{
printf("ok1\n");
struct itimerspec its;
memset((void*)&its, 0, sizeof(its));
printf("tv_sec %d tv_nsec %d tv_sec2 %d tv_nsec2 %d\n",its.it_value.tv_sec,its.it_value.tv_nsec,its.it_interval.tv_sec,its.it_interval.tv_nsec);
printf("disarming timer %ju\n",timer_id);
if(timer_settime(timer_id, 0, &its, NULL) == -1)
err_exit("disarming timer\n");
if (timer_delete(timer_id) == -1){
printf("errno code: %d\n",errno);
err_exit("timer_settime");
}
printf("ok2\n");
printf("delete timer\n");
}
void* thread(void* arg)
{
(void) arg;
sleep(10);
printf("awake thread\n");
return NULL;
}
int main()
{
struct sigaction sa;
struct itimerspec ts[10];
struct sigevent sev[10];
timer_t timer_id[10];
int j;
handle_signal(&sa);
for(j = 0; j < 10; j++){
create_timer(&(sev[j]),&(timer_id[j]),j);
initialize_timerspec(&(ts[j]));
set_timer(&(timer_id[j]),&(ts[j]),j);
reset_timer(timer_id[j],j);
}
sleep(10);
printf("d = %d\n",d);
printf("received signal %d times\n",x);
exit(EXIT_SUCCESS);
}