我想更好地理解RTOS,因此开始实现调度程序。我想测试我的代码,但不幸的是我现在没有硬件。假装执行与 C 中的计时器对应的 ISR 的简单方法是什么?
编辑:多亏了Sneftel的回答,我能够模拟计时器中断。下面的代码受到 http://www.makelinux.net/alp/069 的启发。我唯一缺少的就是以嵌套的方式进行。因此,如果 ISR 正在运行另一个计时器中断,则会导致 ISR 的新实例抢占第一个实例。
#include<stdlib.h>
#include<stdio.h>
#include<assert.h>
#include<signal.h>
#include<sys/time.h>
#include<string.h>
#ifdef X86_TEST_ENVIRONMENT
void simulatedTimer(int signum)
{
static int i=0;
printf("System time is %d.n", i);
}
#endif
int main(void)
{
#ifdef X86_TEST_ENVIRONMENT
struct sigaction sa;
struct itimerval timer;
/* Install timer_handler as the signal handler for SIGVTALRM. */
memset (&sa, 0, sizeof (sa));
sa.sa_handler = &simulatedTimer;
sigaction (SIGVTALRM, &sa, NULL);
/* Configure the timer to expire after 250 msec... */
timer.it_value.tv_sec = 0;
timer.it_value.tv_usec = CLOCK_TICK_RATE_MS * 1000;
/* ... and every 250 msec after that. */
timer.it_interval.tv_sec = 0;
timer.it_interval.tv_usec = CLOCK_TICK_RATE_MS * 1000;
/* Start a virtual timer. It counts down whenever this process is executing. */
setitimer (ITIMER_VIRTUAL, &timer, NULL);
#endif
#ifdef X86_TEST_ENVIRONMENT
/* Do busy work. */
while (1);
#endif
return 0;
}
POSIX 术语中最接近的东西可能是信号处理程序;SIGALRM 在进程中异步触发的方式与 ISR 大致相同。不过,在安全的做法方面存在显着差异,所以我不会用这个类比走得太远。