[英]how to solve the linux timer signal handler
為什么不可能有一個帶有單個處理程序的多重計時器。 我從下面的鏈接使用了該程序,但無法正常工作。 他已經解釋了有關該問題的原因,但並不清楚。 有人幫我為什么它不起作用嗎? http://www.graphics-muse.org/wp/?p=868
如果您的sigval
結構包含足夠的信息以根據您的處理程序中的需要在它們之間進行區分,則沒有理由您不能使用同一處理程序使用timer_create
創建多個計時器。
本文的重點是可能有多個計時器觸發同一個處理程序,但是您需要根據一些傳遞的數據來區分它們。 奇怪的是,作者使用的示例僅占代碼說明距離的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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.