我定义并从 main 调用函数 initialize_timer 两次。成功或失败取决于我两次调用同一函数的顺序。也就是说,当我从 initialize_timer 调用 timer_settime 时,它第一次返回 0。然后,第二次,它返回 -1。
所以重申一下:如果我调用函数 initialize_timer 两次,对函数 timer_settime 的调用返回错误 1 。如果我只是颠倒两个调用的顺序(参见下面的 main),那么它会返回没有错误(0 作为返回值)。
由于函数 initialize_timer 中的所有变量都是局部变量,我猜错误在于我在 main 中调用 calloc 的方式。
有人可以告诉我这是什么错误吗?
为什么我的 initialize_timer 函数中对函数 timer_setttime 的第二次调用失败?
提前致谢。
void initialize_timer(timer_t * tid, int seconds)
{
struct itimerspec * ts;
struct sigaction * sa;
struct sigevent * sev;
ts = malloc(sizeof(struct itimerspec));
sa = malloc(sizeof(struct sigaction));
sev = malloc(sizeof(struct sigevent));
if (tid == NULL)
fprintf(stderr,"malloc");
/* Establish handler for notification signal */
sa->sa_flags = SA_SIGINFO;
if(seconds == 2){
sa->sa_sigaction = producer;
printf("producer was created\n");
}
if(seconds == 6){
sa->sa_sigaction = consumer;
printf("consumer was created\n");
}
sigemptyset(&sa->sa_mask);
if (sigaction(TIMER_SIG, sa, NULL) == -1)
fprintf(stderr,"sigaction");
/* Create and start one timer for each command-line argument */
sev->sigev_notify = SIGEV_SIGNAL; /* Notify via signal */
sev->sigev_signo = TIMER_SIG; /* Notify using this signal */
itimerspec( ts, seconds);
sev->sigev_value.sival_ptr = &tid;
/* Allows handler to get ID of this timer */
if (timer_create(CLOCK_REALTIME, sev, tid) == -1)
fprintf(stderr,"timer_create");
int error=timer_settime(tid, 0, ts, NULL) == -1;
if (error!=0)
fprintf(stderr,"error timer_settime");
}
int main(int argc, char *argv[])
{
pthread_t t1, t2;
int s = 0;
timer_t *tidlist;
tidlist = calloc(2, sizeof(timer_t));
if (tidlist == NULL)
fprintf(stderr, "malloc");
create_threads(&t1, &t2);
initialize_timer(tidlist + 1, 6); //initilize timer for consumer
initialize_timer(tidlist, 2); //initilize timer for producer
s = pthread_join(t1, NULL);
if (s != 0)
fprintf(stderr, "pthread_join");
s = pthread_join(t2, NULL);
if (s != 0)
fprintf(stderr, "pthread_join");
printf("glob = %d\n", glob);
return 1;
}
void itimerspec(struct itimerspec *tsp, int seconds){
tsp->it_value.tv_sec = seconds;
tsp->it_value.tv_nsec = 0;
tsp->it_interval.tv_sec = seconds;
tsp->it_interval.tv_nsec = 0;
}