【发布时间】:2013-10-16 02:49:00
【问题描述】:
我定义并从 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;
}
【问题讨论】:
-
您可能希望将对
fprintf(stderr, <error message)的调用替换为perror(<error message>),以接收有关失败原因的更详细信息。 -
itimerspec()的代码似乎也相关。 -
if(tid == NULL) fprintf(stderr, "malloc")在initializer_timer中似乎也不对,因为 tid 是从外部给出的。您应该检查每个 malloc 中的ts、sa和sev。 -
您是否知道您只能为同一信号安装一个信号处理程序(只有最后一个有效)?
TIMER_SIG是什么?
标签: c++ c multithreading posix