在 C 中模拟硬件定时器中断

Simulate a Hardware Timer Interrupt in C

我想更好地理解 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 大致相同的方式异步触发。不过,在安全操作方面存在显着差异,因此我不会在类比中走得太远。