Timer_create和timerid是允许的吗?

timer_create and timerid, is this allowed?

本文关键字:create timerid Timer      更新时间:2023-10-16

我不能将evp参数设置为NULL,但我想在我的计时器处理程序中接收timerid,就像它被设置为NULL一样。我正在考虑打电话:

struct sigevent se;
se.sigev_notify = SIGEV_THREAD;
se.sigev_notify_attributes = {};
se.sigev_notify_function = timer_handler;
timer_create(CLOCK_MONOTONIC, &se, &se.sigev_value);

我不确定,我是否应该这样做,即使它工作。是否有另一种方法来获得timerid在定时器处理程序,不设置evpNULL ?

这肯定是无效的,因为timer_t可能比int长。另外,将指针传递给联合类型与将指针传递给联合类型的成员也不一样。

你需要这样做:

timer_t timerid;
struct sigevent se = { 0 };
se.sigev_notify = SIGEV_THREAD;
se.sigev_value.sival_ptr = &timerid;
se.sigev_notify_function = timer_handler;
if (timer_create(CLOCK_MONOTONIC, &se, &timerid) < 0)
    abort(); // or whatever
// later...
if (timer_delete(timerid) < 0)
    abort();

换句话说,您需要分配空间来容纳timerid,在sigevent结构中存放指向它的指针,并在使用完计时器后记得删除它。

还应该经常检查系统调用是否有错误,并做一些事情,而不是像什么都没发生一样继续进行。