第五章学习笔记

@

一、学习笔记

1.硬件定时器

定时器由时钟源和可编程计数器组成。时钟源会产生周期性电信号。计数器减为0时,计数器向CPU生成一个定时器中断,计数器周期称为定时器刻度,是系统的基本计时单元。

2.个人计时定时器

实时时钟(RTC)
即使在个人计算机关机时,它也能连续运行。它用于实时提供时间和日期信息。

可编程间隔定时器(PIT)
PIT与CPU分离,提供以毫秒为单位的定时器刻度,在所有I/O设备中,PIT可以最高优先级IRO0中断,PIT定时器中断由Linux内核的定时器中断处理程序来处理。
多核CPU中的本地计时器
每个核都是一个独立的处理器,有自己的本地计时器。
高分辨率计时器
时间戳定时器(TSC)不适合作为实时设备,可提供纳秒级的定时器分辨率。

3.CPU操作和中断处理

由于无效地址、非法指令、越权等问题,可能会出现异常或陷阱。CPU会异常处理程序,当指令执行结束时,CPU会检查挂起的中断。如果有中断请求,但CPU未处于接受中断的状态,CPU会忽略中断,继续执行指令。
中断处理和异常处理在操作系统内核中进行。对于每个中断,可以编程中断控制器来生成唯一的中断向量,标识中断源。CPU会用它作为中断向量表,其中包含指向中断处理程序入口地址的指针,终端结束后,CPU恢复指令正常执行。

4.时钟服务函数

时钟服务可以通过系统调用、库函数和用户级命令调用
gettimeofday-settimeofday函数,gettimeofday()函数用于返回当前时间(当前秒的秒和微秒)。settimeofday()函数用于设置当前时间。在Unix/Linux中,时间表示自1970年1月1日00:00:00起经过的秒数。它可以通过库函数ctime(&time)转换为日历形式。
gettimeofday-settimeofday函数头文件如下:

include <sys/time.h>

int gettimeofday(struct timeval *tv, struct timezone *tz);
int settimeofday(const struct timeval *tv, const struct timezone *tz);
1.gettimeofday()函数:
代码:

include <sys/time.h>

include <unistd.h>

main()
{
struct timeval tv;
gettimeofday(&tv,NULL);
printf("tv_sec : %d\n", tv.tv_sec);
printf("tv_usec : %d\n", tv.tv_usec);
}
settimeofday()函数:
代码:

include <stdio.h>

include <stdlib.h>

include <sys/time.h>

include <time.h>

struct timeval t;

int main()
{
int r;
t.tv_sec=123456789;
t.tv_usec=0;
r=settimeofday(&t,NULL);
if(!r)
{
printf("settimeofday() failed\n");
exit(1);
}
gettimeofday(&t,NULL);
printf("sec=%ld usec=%ld\n",t.tv_sec,t.tv_usec);
printf("%s",ctime(&t.tv_sec));
}
time()函数:
代码:

include <stdio.h>

include <time.h>

int main()
{
time_t seconds;
seconds = time(NULL);
printf("%ld seconds has passed since 1970.1.1\n",seconds);
printf("%ld hours has been passed since 1970.1.1\n",seconds/3600);

return(0);

}

二、苏格拉底挑战

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

三、实践过程及截图

实践代码:

include <signal.h>

include <stdio.h>

include <sys/time.h>

include <time.h>

int count = 0;
struct itimerval t;
time_t start,end ;
void timer_handler(int sig){
end =time(NULL);
printf("timer_handler : signal %d count=%d , diff: %ld \n",sig, ++count,end -start);
start = end;
if( count >= 8){
printf("cancel timer \n");
t.it_value.tv_sec = 0 ;
t.it_value.tv_usec = 0;
setitimer(ITIMER_VIRTUAL, &t , NULL);
}
}

int main(){
struct itimerval timer ;
signal (SIGVTALRM ,timer_handler);
timer.it_value.tv_sec = 0;
timer.it_value.tv_usec = 100000;
//every 1s afterward
timer.it_interval.tv_sec = 1;
timer.it_interval.tv_usec = 0;
// start a virtual itimer
start = time(NULL);
setitimer( ITIMER_VIRTUAL , &timer ,NULL );
printf("press Ctrl + C to terminate \n");
while(1);
}
截图
在这里插入图片描述

posted @ 2023-12-17 21:08  20211112周子凯  阅读(6)  评论(0编辑  收藏  举报