2

实际上我想实现非阻塞定时器,当定时器到期时,一个处理程序将被调用并会做一些事情(现在它打印数据)。我谷歌并意识到timer_createtimer_settimer是非阻塞计时器。但是我仍然有问题,我必须等待我的计时器到期(sleep(MAX)while(1) {;})。但是,如果我start_timer用不同的“到期”时间调用我的方法,它应该相应地工作,不应该阻止其他。例如,在这里我第一次调用计时器,并期望在 5 秒内调用处理程序,但在第二次调用之前应该打印其数据,因为我给出的间隔仅为 1 秒。当然,它的行为也不一样。任何想法?

#include <time.h>
#include <stdio.h>
#include <signal.h>
#include <pthread.h>
#include <unistd.h>
#include <errno.h>

typedef struct _data{
    char *name;
}data;


void handler(union sigval val)
{
    data *data_handler = val.sival_ptr;
    printf("Handler entered with value :%s\n", data_handler->name);
}

void mod_timer(timer_t timerid, struct sigevent sig, struct itimerspec in, struct itimerspec out)
{
    printf("mod_timer\n");
    timer_settime(timerid, 0, &in, &out);
    while(1)
        sleep(1);
    //delete the timer.
    timer_delete(timerid);
}

void start_timer(void* val, int interval)
{
    int Ret;
    pthread_attr_t attr;
    pthread_attr_init( &attr );

    struct sched_param parm;
    parm.sched_priority = 255;
    pthread_attr_setschedparam(&attr, &parm);

    struct sigevent sig;
    sig.sigev_notify = SIGEV_THREAD;
    sig.sigev_notify_function = handler;
//    sig.sigev_value.sival_int = val;
    sig.sigev_value.sival_ptr = val;
    sig.sigev_notify_attributes = &attr;

//create a new timer.
    timer_t timerid;
    Ret = timer_create(CLOCK_REALTIME, &sig, &timerid);
    if (Ret == 0)
    {
        struct itimerspec in, out;
        in.it_value.tv_sec = 1;
        in.it_value.tv_nsec = 0;
        in.it_interval.tv_sec = interval;
        in.it_interval.tv_nsec = 0;

       mod_timer(timerid, sig, in, out);
    }
}

void main()
{
//    start_timer(1, 5);
//    start_timer(2, 1);
    data handler_data1 = {"Handler Data 1"};
    data handler_data2 = {"Handler Data 2"};
    void *data1 = &handler_data1;
    void *data2 = &handler_data2;
    start_timer(data1, 5);
    start_timer(data2, 1);
}
4

1 回答 1

0

您可以使用该alarm函数生成信号,并使用该signal函数指定该信号的处理程序。

于 2012-12-10T14:06:29.570 回答