2014-02-27 44 views

回答

2

沒有理由你不能使用相同的處理器與timer_create創建多個定時器,提供您sigval結構包含足夠的信息,根據需要在你的處理器來區分它們。

+0

你檢查了我的問題上面的鏈接??你可以做到!但在某些情況下,這是不可能的 – user3354789

+0

我認爲我的觀點與他相同。您的處理程序需要區分哪些計時器正在關閉。 – abligh

+0

@ user3354789,abligh是正確的。您需要將開關從認爲正確的方向轉換爲理解錯誤的原因。公平地說,這個例子中的代碼是相當糟糕的,並且只是3/4的方式來說明事情的工作方式。 – Duck

1

文章的要點是它可能有多個定時器觸發相同的處理程序,但您需要根據一些傳遞的數據來區分它們。奇怪的是,作者使用的例子只是在代碼中說明這個距離的3/4,所以也許這是你的困惑的根源。

希望這篇文章的程序改造更清晰一些。它使用sival_ptr指向一個字符串,但它可以指向任何類型。這是定時器如何區分的。

#define _POSIX_C_SOURCE 199309 
#include <stdio.h> 
#include <signal.h> 
#include <unistd.h> 
#include <stdlib.h> 
#include <time.h> 

#define errExit(msg) do { perror(msg); exit(EXIT_FAILURE); } while (0) 

void timerHandler(int sig, siginfo_t *si, void *uc) 
{ 
    // obligator caution not to use printf and other async-unsafe calls 
    // in a handler in real programs 

    printf("I am timer %s\n", (char *) si->si_value.sival_ptr); 
} 

void makeTimer(char *name, int intervalMS) 
{ 
    struct sigevent   te; 
    struct itimerspec  its; 
    struct sigaction  sa; 
    int      sigNo = SIGRTMIN; 

    // Set up signal handler. 
    sa.sa_flags = SA_SIGINFO; 
    sa.sa_sigaction = timerHandler; 
    sigemptyset(&sa.sa_mask); 

    if (sigaction(sigNo, &sa, NULL) == -1) 
     errExit("sigaction"); 

    // Set up timer 
    te.sigev_notify = SIGEV_SIGNAL; 
    te.sigev_signo = sigNo; 
    te.sigev_value.sival_ptr = name; 

    timer_t timerID; 

    if (timer_create(CLOCK_REALTIME, &te, &timerID) == -1) 
     errExit("timer_create"); 

    its.it_value.tv_sec = intervalMS; 
    its.it_value.tv_nsec = 0; 
    its.it_interval.tv_sec = 0; 
    its.it_interval.tv_nsec = 0; 

    if (timer_settime(timerID, 0, &its, NULL) == -1) 
     errExit("timer_settime"); 

    return; 
} 

int main(int argc, char *argv[]) 
{ 
    char *arr[3] = {"number one", "number two", "number three"}; 

    makeTimer(arr[0], 1); 
    makeTimer(arr[1], 2); 
    makeTimer(arr[2], 3); 

    while (sleep(5)); 

    return(0); 
} 
+0

但是如何調用每2ms,10ms和100ms的特定任務? – user3354789

+0

你的代碼與我上面發佈的鏈接有什麼不同? – user3354789

+0

我所做的更改主要是取出無關的東西,並將ptr更改爲指向字符串,而不是定時器ID以簡化如何完成的說明。至於你之前的pgm中的具體任務,你需要循環執行。您只需設置一次定時器並設置間隔,以便重複觸發。 – Duck