我有这个 C++ 程序。它有一个简单的 for 循环,打印从 1 到 20 的数字。在此期间,执行期间,计时器多次到期,每次到期时,它应该打印信号处理程序的输出。
不幸的是我没有得到这个输出。它只是简单地打印从 1 到 20 的数字。有人可以帮我吗?
提前致谢
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
#include <time.h>
#define CLOCKID CLOCK_REALTIME
#define SIG SIGRTMIN
#define errExit(msg) do { perror(msg); exit(EXIT_FAILURE); \
} while (0)
#include <iostream>
using namespace std;
static int flag=0;
class timer{
static void
handler(int sig) {
printf("Caught signal %d\n", sig);
::flag=1;
signal(sig, handler);
}
public:
void timer_func()
{
timer_t timerid;
struct sigevent sev;
struct itimerspec its;
long long freq_nanosecs=1; // The timer frequency in nanosecs
sigset_t mask;
struct sigaction sa;
/* Establish handler for timer signal */
printf("Establishing handler for signal %d\n", SIG);
sa.sa_flags = SA_RESETHAND;
sa.sa_handler = handler;
/* Create the timer */
sev.sigev_notify = SIGEV_SIGNAL;
sev.sigev_signo = SIG;
sev.sigev_value.sival_ptr = &timerid;
if (timer_create(CLOCKID, &sev, &timerid) == -1)
errExit("timer_create");
printf("timer ID is 0x%lx\n", (long) timerid);
/* Start the timer */
its.it_value.tv_sec = freq_nanosecs / 1000000000;
its.it_value.tv_nsec = freq_nanosecs % 1000000000;
its.it_interval.tv_sec = its.it_value.tv_sec;
its.it_interval.tv_nsec = its.it_value.tv_nsec;
if (timer_settime(timerid, 0, &its, NULL) == -1)
errExit("timer_settime");
}
};
int main() {
timer ob;
ob.timer_func();
for(int i=0; i<20; i++) {
sleep(1);
if(flag) {
cout << "Timer called" << endl;
flag=0;
}
cout << "Printing i: " << i << endl;
}
}
但是如果我在其中设置“long long freq_nanosecs = 1”,定时器也只会输出一次。应该重复
最佳答案
0.011 是一个双字面量,您将它分配给一个 long,因此它被转换为 0。这只是将 freq_nanosecs 设置为 0。
long freq_nanosecs=0.011
由于定时器值为 0,这将解除定时器。
timer_settime(timerid, 0, &its, NULL)
关于C++(在 Linux 下)程序没有给出预期的输出(定时器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5140199/