Linuxのタイマハンドラを利用してインターバルタイマを使おうと思ったのですがクラス内関数をハンドラに登録が出来ない事が分かり困っています。
下記に状況を再現したコードとコンパイルエラーの内容を添付します。
ライブラリの変更等も含めてこの状況を解決できる方法は何か無いでしょうか。
C++
1 2#include <sys/time.h> 3#include <signal.h> 4#include <string.h> 5#include <iostream> 6#include <time.h> 7 8 9class timer_test{ 10private: 11 struct sigaction action; 12 struct itimerval timer; 13 struct timespec timer_count, last_time_timer_count; 14 int counter = 0; 15 int nsec; 16 17public: 18 timer_test(){ 19 memset(&action, 0, sizeof(action)); 20 } 21 22 23 int timer_start(void){ 24 scheduler_setup(100000); 25 while(counter < 50){ 26 _nanosleep(0, 50); 27 timer.it_interval.tv_usec = 0; 28 timer.it_value.tv_usec = 0; 29 setitimer(ITIMER_REAL, &timer, NULL); 30 } 31 return 0; 32 } 33 34private: 35 int scheduler_setup(int interval_us){ 36 struct sigaction action; 37 // set signal handler 38 action.sa_handler = SignalHandler; 39 action.sa_flags = SA_RESTART; 40 sigemptyset(&action.sa_mask); 41 if(sigaction(SIGALRM, &action, NULL) < 0){ 42 std::cout << "sigaction error" << std::endl; 43 exit(1); 44 } 45 // set intarval timer 46 timer.it_value.tv_sec = 0; 47 timer.it_value.tv_usec = interval_us; 48 timer.it_interval.tv_sec = 0; 49 timer.it_interval.tv_usec = interval_us; 50 if(setitimer(ITIMER_REAL, &timer, NULL) < 0){ 51 std::cout << "setitimer error" << std::endl; 52 return 1; 53 } 54 clock_gettime(CLOCK_REALTIME, &last_time_timer_count); 55 return 0; 56 } 57 58 59 void SignalHandler(int signum){ 60 static unsigned long cnt = 1; 61 static unsigned long sum = 0; 62 static unsigned int ave = 0; 63 64 clock_gettime(CLOCK_REALTIME, &timer_count); 65 nsec = timer_count.tv_nsec - last_time_timer_count.tv_nsec; 66 if(nsec > 0){ 67 sum += nsec; 68 ave = sum / cnt; 69 cnt++; 70 } 71 std::cout << "SignalHandler:" << nsec / 1000 << "usec\n" << std::endl; 72 std::cout << "ave:" << ave / 1000 << "usec\n" << std::endl; 73 last_time_timer_count = timer_count; 74 counter++; 75 76 return; 77 } 78 79 80 int _nanosleep(int sec, int nsec){ 81 struct timespec req, rem; 82 req.tv_sec = sec; 83 req.tv_nsec = nsec; 84 rem.tv_sec = 0; 85 rem.tv_nsec = 0; 86 while(nanosleep(&req, &rem)){ 87 if(errno == EINTR){ 88 req.tv_sec = rem.tv_sec; 89 req.tv_nsec = rem.tv_nsec; 90 }else{ 91 perror("nanosleep error"); 92 return -1; 93 } 94 } 95 return 0; 96 } 97}; 98 99 100int main(void) 101{ 102 timer_test *t = new timer_test(); 103 t -> timer_start(); 104 return 0; 105} 106
$ g++ timer_test.cpp -std=c++11
timer_test.cpp: In member function ‘int timer_test::scheduler_setup(int)’: timer_test.cpp:38:27: error: cannot convert ‘timer_test::SignalHandler’ from type ‘void (timer_test::)(int)’ to type ‘__sighandler_t {aka void (*)(int)}’ action.sa_handler = SignalHandler; ^
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2021/06/27 10:24
2021/06/27 11:49
2021/06/27 12:42