2011-05-10 40 views
3

我正在使用timer_create在Linux中創建計時器。回調原型:使用timer_create傳遞用戶數據

static void TimerHandlerCB(int sig, siginfo_t *extra, void *cruft) 

如何傳遞用戶數據,這樣我可以在定時器超時後調用的回調收到相同。

這裏是我的示例代碼:

int RegisterTimer(iDiffInTime) 
{ 
    struct sigaction sa; 
    sigemptyset(&sa.sa_mask); 
    sa.sa_flags = SA_SIGINFO; /*call our handler*/ 
    sa.sa_sigaction = TimerHandlerCB;/*Event handler to be called after timer expires*/ 
    if(sigaction(SIGRTMAX, &sa, NULL) < 0) 
    { 
     perror("sigaction"); 
     return 1; 
    } 
    // Setup the timer 
    sigevent sigev; 
    timer_t timerid = 0; 

    memset(&sigev, 0, sizeof(sigev)); 

    sigev.sigev_notify   = SIGEV_SIGNAL; 
    sigev.sigev_signo   = SIGRTMAX; 
    sigev.sigev_value.sival_ptr = &timerid; 

    timer_t timerid; 

    if (timer_create(CLOCK_REALTIME, &sigev, &timerid) == 0) 
    { 
     printf("Timer created\n"); 
     struct itimerspec itval, oitval; 

     itval.it_value.tv_sec = iDiffInTime * 1000; 
     itval.it_value.tv_nsec = 0; 
     itval.it_interval.tv_sec = 0; 
     itval.it_interval.tv_nsec = 0; 

       //Populate handles required in TimerCallback 
       Display_Handle hDisplay = ......// 
       Buffer_Handle hBuf = .....// 
     if (timer_settime(timerid, 0, &itval, &oitval) != 0) 
     { 
      perror("time_settime error!"); 
      return 1; 
     } 
    } 
    else 
    { 
     perror("timer_create error!"); 
    } 
    return 0 
} 

從哪裏傳hDisplay & hBuf,這樣我可以接受他們回到TimerHandlerCB

+0

C或C++的的timerId結構 的地址?選一個。 – 2011-05-10 09:05:50

+0

@Tomalak Geret'kal:它是一個帶有程序C++的遺留代碼;) – 2011-05-10 09:16:13

+0

將'.sival_ptr'設置爲局部變量的地址可能不是一個好主意。 – PSkocik 2017-11-14 17:27:03

回答

3

你已經在做了:

sigev.sigev_value.sival_ptr = &timerid; 

你可以指定任何內容(指定&timerid是通常在多個定時器之間辨別,但不是必需的)。現在,在你的處理器:從TLPI

static void timer_handler(int signo, siginfo_t *si, void *uc) 
{ 
    /* si->si_value.sival_ptr */ 
} 

報價在調用timer_create(), evp.sigev_value.sival_ptr通常 分配在同一個呼叫給出的timerId 參數的地址。 或者, evp.sigev_value.sival_ptr可以 分配包含給予 timer_create()

+0

謝謝這就是我需要:) – 2011-05-10 09:56:56

1

您需要:

  • 添加全局變量,並使用一些同步機制就像信號燈
  • 使用sigqueue