【问题标题】:timer_settime fails even though all members of the itimerspec are set即使设置了所有 itimerspec 成员, timer_settime 也会失败
【发布时间】:2012-10-05 20:53:44
【问题描述】:

所以,直到最近,当我们决定将其移至 Lubuntu 12.04 系统时,这段代码才能正常工作。对 timer_settime 的调用返回 EINVAL,并在 gdb 下运行我已经确认 ts 的所有字段在调用时都在 0 和 999999999 之间:

1067        if(-1 ==timer_settime(tid,0,&ts,NULL))
(gdb) print ts
$1 = {it_interval = {tv_sec = 0, tv_nsec = 200000000}, it_value = {tv_sec = 0,
tv_nsec = 0}}

既然这应该是唯一可以导致它返回 EINVAL 的东西,我非常困惑。也许这里有一些明显的东西我错过了。

struct sigevent sev;
struct itimerspec ts;
timer_t *tid;
//actually point the pointer at something.
tid = calloc(1,sizeof(timer_t));
//make sure there's no garbage in the structures.
memset(&sev,0,sizeof(struct sigevent));
memset(&ts,0, sizeof(struct itimerspec));
//notify via thread
sev.sigev_notify = SIGEV_THREAD;
sev.sigev_notify_function = SwitchThreadHandler;
sev.sigev_notify_attributes = NULL;
sev.sigev_value.sival_ptr = tid;
ts.it_value.tv_sec =0;
ts.it_value.tv_nsec = 0;
ts.it_interval.tv_sec = 0;
ts.it_interval.tv_nsec = 200000000;
if(-1 == timer_create(CLOCK_REALTIME,&sev,tid))
{
    retval = EX_SOFTWARE;
    fprintf(stderr,"Failed to create timer.");
    free(tid);
    return retval;
}

if(-1 ==timer_settime(tid,0,&ts,NULL))
{
    int errsv = errno;
    fprintf(stderr,"timer_settime FAILED!!!\n");
    if(errsv == EINVAL)
    {
        fprintf(stderr,"INVALID VALUE!\n");
    }
    else
    {
        fprintf(stderr,"UNKOWN ERROR: %d\n",errsv);
    }
    return EX_SOFTWARE;
}

【问题讨论】:

    标签: c timer posix errno


    【解决方案1】:

    timer_settime 被记录为将timer_t 作为第一个参数,而不是像timer_create 这样的timer_t *。如果timerid 无效,它将失败并显示EINVAL。

    因此,您应该将*tid 作为第一个参数传递。

    请注意,您的编译器应该对此发出警告。

    【讨论】:

    • 奇怪的是,gcc -Wall 并没有对此一视同仁,它在我们尝试过的四种环境中的三种环境中都能完美运行。诡异的。好吧,现在它不再失败,但计时器永远不会触发,所以你已经回答了我提出的问题。
    • timer_t 在 linux 上为 void*,因此 timer_settime 将接受任何指针作为第一个参数而不会发出警告。
    猜你喜欢
    • 2018-11-18
    • 2020-10-03
    • 1970-01-01
    • 2017-12-08
    • 2017-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-22
    相关资源
    最近更新 更多