c - 即使设置了 itimerspec 的所有成员,timer_settime 也会失败

标签 c timer posix errno

因此,直到最近我们决定将其移至 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;
}

最佳答案

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

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

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

关于c - 即使设置了 itimerspec 的所有成员,timer_settime 也会失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12753883/

相关文章:

c - 免费功能的使用

c - 如何实现这个函数的递归版本

iOS 我们可以重用 NSTimer

javascript - 单击按钮永久删除计时器

c - 访问另一个进程中的共享内存缓冲区

c - 在不同的字节范围内读取和写入同一个文件是否线程安全?

c - 如何读取不同格式的行

jakarta-ee - 使用有状态 ejb 的 TimerService 的解决方法

无法在 C 中使用 system() 函数执行 "cat"

c - Malloc() 不起作用 + 字符数组清除