【问题标题】:How to compile POSIX timer如何编译 POSIX 计时器
【发布时间】:2014-03-18 17:01:34
【问题描述】:

我正在尝试在多线程程序中使用 POSIX 计时器创建超时函数 (enable_timeout)。我需要强制该函数的调用线程是接收和处理SIGALRM 信号的线程。为此,我有以下代码,它基于 man timer_create 并进行了一些修改:

void procman_enable_timeout(int msec)
{
    timer_t timerid;
    struct sigevent sev;
    struct itimerspec its;

    // Disable the signal:
    procman_sig_disable(SIGALRM);

    // Will send the signal to the calling thread.
    sev.sigev_notify = SIGEV_THREAD_ID;
    sev.sigev_notify_thread_id = syscall(SYS_gettid);
    // Signal to be sent:
    sev.sigev_signo = SIGALRM; 
    sev.sigev_value.sival_ptr = &timerid;

    // Create the timer:
    timer_create(CLOCK_REALTIME, &sev, &timerid); // Does not start it. 


    // Configure the timer to expire after the specified interval:
    its.it_value.tv_sec = (msec/1000);
    its.it_value.tv_nsec = (msec*1000000)%1000000;
    // Will not be periodic:
    its.it_interval.tv_sec = 0;
    its.it_interval.tv_nsec = 0;

    // Install and enable signal handler:
    sigalrm_catched = false;
    procman_sig_enable(SIGALRM);

    // Start timer:
    timer_settime(timerid, 0, &its, NULL);

    while(!sigalrm_catched)
        pause(); // Waits for the reception of a SIGALRM (or any other signal!)
    sigalrm_catched = false;

    // Disable signal handler:
    procman_sig_disable(SIGALRM);
}

但是,当我尝试编译它(使用-lrt 选项)时,GCC 会输出以下内容:

procman.c:137:8: error: ‘struct sigevent’ has no member named ‘sigev_notify_thread_id’
 sev.sigev_notify_thread_id = syscall(SYS_gettid);
    ^

我错过了什么?我包括了time.hsignals.h。它不应该工作吗?

编辑:我也在使用pthread_mutex_init(&mutex, PTHREAD_MUTEX_ERRORCHECK)@alk 建议将 POSIX.1b 定义为包含 POSIX 计时器,但这删除了此功能。

【问题讨论】:

  • 你在 Linux 上,是吗?
  • 您可能需要定义 #define _POSIX_C_SOURCE 199309L 才能使用 POSIX 计时器等。
  • 是的,我在 Linux 上,抱歉我没有提到!将 POSIX 标准定义为 199309L 解决了这个问题。但是,它让我失去了 PHTREAD_MUTEX_ERRORCHECK 功能。有办法保存吗?
  • 请看我的回答。

标签: c linux multithreading timer posix


【解决方案1】:

要使 POSIX 计时器事件可用,定义 _POSIX_C_SOURCE 需要设置为至少 199309L

 #define _POSIX_C_SOURCE 199309L

对于最新的 POSIX 功能,您可以尝试将其设置为 200809L,例如

#define _POSIX_C_SOURCE 200809L

有关各种可能性的详细信息,请参阅:http://man7.org/linux/man-pages/man7/feature_test_macros.7.html

【讨论】:

  • 这正是我的想法,但它产生了以下输出:proccman_time.c:35:8: error: ‘struct sigevent’ has no member named ‘sigev_notify_thread_id’procman_time.c:35:5: warning: implicit declaration of function ‘syscall’ [-Wimplicit-function-declaration]
  • #define sigev_notify_thread_id _sigev_un._tid 将编译该程序,尽管我不确定这是否是一个好的方法(我在 Cyclictest 来源中找到了它:svn.gna.org/svn/xenomai/trunk/src/testsuite/cyclic/cyclictest.c
  • @CarlesAraguz:要使syscall() 可用,您需要在#include 之前#define _GNU_SOURCE 使用适当的标题:man7.org/linux/man-pages/man2/syscall.2.html
猜你喜欢
  • 2012-02-18
  • 1970-01-01
  • 1970-01-01
  • 2013-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多