内核的定时机制实验

来源:互联网 发布:讲故事软件哪个好 编辑:程序博客网 时间:2024/05/23 01:18

一.实验目的

本实验是练习怎样编写调用内核的时间测量功能为应用程序测量和精确定时。通过这个实验我们可以进一步理解Linux内核的定时机制及其数据结构以及怎样从用户空间去访问内核空间的时间数据。

二.实验问题

1、使用操作系统提供的定时机制实现一个精确到微秒级的闹钟

2、支持用户设置最多4个闹铃

三.实验代码

#include<stdio.h>#include<unistd.h>#include<signal.h>#include<string.h>#include<fcntl.h>#include<stdlib.h>#include<pthread.h>#include<sys/time.h>int count=0;struct timeval thetime;//信号发生函数void handle(int num){count++;printf("The %d time is over\n",num);}//求去当前时间和闹钟时间的时间差,精确到微妙struct timeval nowtime(int b[4]){int a[3];time_t   now;       struct   tm     *timenow; char s[100];time(&now);timenow   =   localtime(&now);strcpy(s,asctime(timenow));a[0]=(s[11]-48)*10+s[12]-48;a[1]=(s[14]-48)*10+s[15]-48;a[2]=(s[17]-48)*10+s[18]-48;thetime.tv_sec=(b[0]-a[0])*3600+(b[1]-a[1])*60+b[2]-a[2];thetime.tv_usec=b[3];return thetime;}//建立闹钟,并行处理void deal(){struct itimerval tick;tick.it_interval.tv_usec=0;tick.it_interval.tv_sec=0;int i;tick.it_value.tv_sec=thetime.tv_sec;tick.it_value.tv_usec=thetime.tv_usec;if(fork()){signal(SIGALRM,handle);setitimer(ITIMER_REAL,&tick,NULL);while(1)pause;}}void main(){int num,i,j;int a[4];//输入闹钟个数printf("Please input the space interval:\n");scanf("%d",&num);for(i=0;i<num;i++){scanf("%d:%d:%d %d",&a[0],&a[1],&a[2],&a[3]);handle(i+1);thetime=nowtime(a);deal();}}

       在Linux中,存在三种定时机制ITIMER_REAL,ITIMER_VIRTUAL和ITIMER_PROF,他们各自有不同的作用,每个定时都要设定一个值,然后随时间递减,当递减到0时,闹钟就会被触发。在代码中,利用time_t数据结构,可以得到毫秒级的时间,当前时间可以获得,再将闹钟时间转化为秒级和毫秒,相减,会获得一个毫秒级时间差。再把这个时间差作为setitimer函数的参数,依次递减,直到为0触发闹钟。

       在实验中,要求要最多设置4个闹钟,所以每个闹钟要并行处理,互不干涉。所以要为每个闹钟设置一个进程,在这个闹钟信号触发后,杀死进程,本次闹钟结束。


20110105


原创粉丝点击