相关结构类型声明如下: struct itimerval{
struct timeval it_interval; struct timeval it value; }
getitimer 函数得到间隔计时器的时间值并保存在 value 中。setitimer 函数设置间隔计 时器的时间值为 newval,并将旧值保存在 oldval 中。which 表示使用三个计时器中的哪一 个。itimerval 结构中的 it_value 是减少的时间,当这个值为 0 的时候就发出相应的信号了,然后设置为 it_interval 值。
【实验步骤】
编写 timer.c 程序源代码 #include
struct timeval tpstart,tpend; float
timeuse;
static timer_count = 0;
void prompt_info(int signo) {
time_t t = time(NULL);
/* [1] 2 seconds turned, print something */ printf(\/* [2] get current time and print it */ ctime(&t);
printf(\current time %s\/* [3] stop get time, and print it */ gettimeofday(&tpend,NULL);
timeuse=1000000*(tpend.tv_sec-tpstart.tv_sec)+tpend.tv_usec-tpstart.tv_usec;
timeuse/=1000000;
printf(\Used Time:%f\\n\}
void init_sigaction(void) {
struct sigaction act; act.sa_handler=prompt_info; act.sa_flags=0; sigemptyset(&act.sa_mask); sigaction(SIGPROF,&act,NULL);
/* begin get the time */ gettimeofday(&tpstart,NULL); printf(\time\\n\
}
void init_time() {
struct itimerval value; value.it_value.tv_sec=2; value.it_value.tv_usec=0; value.it_interval=value.it_value; setitimer(ITIMER_PROF,&value,NULL);
} /*
* timer application code */
int main(int argc, char **argv) {
init_sigaction(); init_time(); while(1); exit(0); }
3、编写 Makefile 文件,Makefile 内容如下: CC=gcc LD=ld
EXEC = timer OBJS = timer.o
CFLAGS += LDFLAGS +=
all: $(EXEC)
$(EXEC): $(OBJS)
$(CC) $(LDFLAGS) -o $@ $(OBJS) $(LDLIBS$(LDLIBS_$@)) clean:
-rm -f $(EXEC) *.elf *.gdb *.o
4、编译timer,在timer目录下,终端输入如下命令: # make clean # make # ./timer 输出结果如下: [1] prompt_info called
current time Sat Mar 30 15:58:23 2005 Used Time:2.003054 [2] prompt_info called
current time Sat Mar 30 15:58:25 2005
Used Time:4.001216 [3] prompt_info called
current time Sat Mar 30 15:58:27 2005 Used Time:6.001144 [4] prompt_info called
current time Sat Mar 30 15:58:29 2005 Used Time:8.001138
该程序正确执行时将每隔两秒钟打印一次上述信息,“prompt_info called”字符串是在定时器处理函数中打印的,还打印了当前系统时间和从第 1 次启动定时器开始获取的时 间间隔。
实验四、设备驱动实验
【实验目的】
通过本实验的学习,了解Linux操作系统中的设备驱动程序包括哪些组成部分,并能编写简单的字符设备(scull,Simple Character Utility for Loading Localities)和块设备(sbull,Simple Block Utility for Loading Localities)的驱动程序以及
对所编写设备驱动程序的测试,最终了解Linux操作系统是如何管理设备的。
【准备知识】
一.设备驱动程序的简单介绍
Linux设备驱动程序集成在内核中,实际上是处理或操作硬件控制器的软件。从本质上讲,驱动程序是常驻内存的低级硬件处理程序的共享库,设备驱动程序就是对设备的抽象处理;也即是说,设备驱动程序是内核中具有高特权级的、常驻内存的、
可共享的下层硬件处理例程。
设备驱动程序软件封装了如何控制这些设备的技术细节,并通过特定的接口导出一个规范的操作集合(见图1);内核使用规范的设备接口(字符设备接口和块设备接口)通过文件系统接口把设备操作导出到用户空间程序中。(由于本实验不涉及网
络设备,故在此就不作讨论)
键硬 串软 并光 其 其
图1 字符(块)设备、驱动
在Linux中,字符设备和块设备的I/O操作是有区别的。块设备在每次硬件操作时把多个字节传送到主存缓存中或从主存缓存中把多个字节信息传送到设备中;而字
符设备并不使用缓存,信息传送是一个字节一个字节地进行的。
Linux操作系统允许设备驱动程序作为可装载内核模块实现,这也就是说,设备的接口实现不仅可以在Linux 操作系统启动时进行注册,而且还可以在Linux 操作
系统启动后装载模块时进行注册。
总之,Linux操作系统支持多种设备,这些设备的驱动程序有如下一些特点: