c - 如何编译 POSIX 定时器

标签 c linux multithreading timer posix

我正在尝试在多线程程序中使用 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 计时器,但这删除了此功能。

最佳答案

要使 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

关于c - 如何编译 POSIX 定时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22486126/

相关文章:

在给定数字 N 后将列更改为行

linux - 从 bash 脚本更改 apache 配置文件值

C++:如何获取文件夹列表

c - 在循环中调用时,excel 返回错误地址

c++ - Qt on VirtualBox 中的 OpenMP 仅使用一个线程

c - 杂项驱动程序和字符驱动程序有什么区别?

c - 包含文件之间的共享变量状态未准确传达

c - 在 C 中对字符数组进行 alpha 排序的最简单方法是什么?

Java:同时移动对象

Java - 多线程服务器仅适用于一个连接