-
POSIX timers in c++
hello all,
I'm using POSIX timers in C++ application, using timer_create() this timer will raise a signal when timer expires and to Handle this I want to use signal handler function (which is in my class method).
To achieve this I need to make this class method as static method, now if I wanna use any attribute in class that should be static variable!!! Is there any alternative method to achieve this ????
Thanks in advance
-
> I want to use signal handler function (which is in my class method).
Which instance (of an object) do you want the signal to apply to?
This only seems to make sense if you have a singleton.
-
You can store a pointer to your class in the sigevent structure, then access that pointer in the signal handler.
Code:
struct sigevent e;
e.sigev_value.sival_ptr = myClassPointer;
// ...
Then in your signal handler:
Code:
void MyClass::StaticHandler(int sig, siginfo_t *si, void *uc)
{
MyClass* c = reinterpret_cast<MyClass*>(si−>si_value.sival_ptr);
c->foo();
}
-
thanks to bithub for your answer.
I tried to solve the problem this way but I got some problems to set up the right signal handler function.
If I tried to set the extended handler function - all I got was this error:
Code:
void Scheduler::tic(int sigNumb, siginfo_t *si, void *uc) {
perror("i was called");
}
this->SignalAction.sa_handler = Scheduler::tic;
error: invalid conversion from 'void (*)(int, siginfo_t*, void*)' to 'void (*)(int)'
Am I right in setting the handler to sa_handler ?
By the way... am I allowed to pass references to class members for setting up the timer, as follows:
Code:
timer_create(CLOCK_REALTIME, &this->signalEvent, &this->timerID)
thanks for your help
-
To use a signalhandler function with the signature
Code:
void func(int signo, siginfo_t *info, void *context)
The flag SA_SIGINFO has to be set in sigaction.sa_flags and the callback-function pointer has to be added to sigaction.sa_sigaction.
Code:
struct sigevent signalEvent;
struct sigaction SignalAction;
// Define sigaction method
this->SignalAction.sa_sigaction = Scheduler::tic;
// set mask empty -> react on all signals
sigemptyset(&this->SignalAction.sa_mask);
this->SignalAction.sa_flags = SA_SIGINFO;
// Define sigEvent
this->signalEvent.sigev_value.sival_ptr = this;
This solved the problem mentioned in my previous post.