內核的定時機制實驗

一.實驗目的

本實驗是練習怎樣編寫調用內核的時間測量功能爲應用程序測量和精確定時。通過這個實驗我們可以進一步理解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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章