首页 > 解决方案 > timer_create 函数返回 EINVAL

问题描述

我正在编写一个示例程序,我的 main() 将创建一个线程,然后它将启动一个计时器。当计时器到期时,线程应该得到信号。这是在 Ubuntu 18.04.4 LTS 上。

我的问题是 timer_create() 失败并且错误号设置为 EINVAL。下面给出了我的 timer_create() 代码片段。

    /* Create the timer */
    sevp.sigev_notify = SIGEV_THREAD_ID;
    sevp.sigev_signo = SIGALRM;
    sevp.sigev_value.sival_int = somevalue;
    sevp._sigev_un._tid = threadid;

    retval = timer_create(CLOCK_MONOTONIC,&sevp,&timerid);

    if ( 0 == retval )
    {
        printf("Success in creating timer [%p]",timerid);
    }
    else
    {
        printf("Error in creating timer [%s]\n",strerror(errno));
    }

我究竟做错了什么?

标签: clinuxtimerlinux-kernel

解决方案


根据timer_createwith的 linux 手册页条目SIGEV_THREAD_ID

至于 SIGEV_SIGNAL,但信号是针对在 sigev_notify_thread_id 中给出的 ID 的线程,该线程必须是与调用者在同一进程中的线程。sigev_notify_thread_id 字段指定内核线程ID,即clone(2) 或gettid(2) 返回的值。此标志仅供线程库使用。

线程 ID(threadid在问题代码中)需要是内核线程 ID。可以使用 获取该 ID gettid


推荐阅读