IoTimer的使用

xiaoxiao2021-02-28  158

IoTimer的使用

IoTimer是系统里面的时钟,比如说我们想要隔一段时间调用一次我们自己写的函数,那么我们就可以设置一个时钟(当然,也可以用DPC,可以参考我前两篇的博客),将所要调用函数和时钟关联,就可以实现自动调用。IoTimer和DPC不同的是,DPC可以自己设定时间,而IoTimer是一秒执行一次所关联的函数(当然,也可以想几秒调一次函数就几秒掉一次函数,下面的例子我是5秒调用一次,默认情况下是1秒调用1次)

步骤:1.创建一个设备对象

2.初始化一个时钟:IoInitializeTimer(DeviceObject, (PIO_TIMER_ROUTINE)TimerRoutine, NULL);

3.IoStartTimer(DeviceObject);//在这之后,例程每秒一次的被调用

4.卸载程序的时候要暂停时钟:IoStopTimer(DriverObject->DeviceObject);

5.卸载程序的时候要删除设备对象

注:同前面所讲的DPC一样,我下一篇会说如何通过其他程序移除我们这个程序的IoTimer

#pragma once #include <ntifs.h> #define DEVICE_NAME L"\\Device\\IoTimerInlineHookDeviceName" VOID TimerRoutine( _In_ struct DEVICE_OBJECT *DeviceObject, _In_opt_ PVOID Context ); VOID DriverUnload(PDRIVER_OBJECT DriverObject); #include"IoTimer.h" ULONG __v1 = 0; NTSTATUS DriverEntry(PDRIVER_OBJECT DriverObject, PUNICODE_STRING RegisterPath) { NTSTATUS Status = STATUS_UNSUCCESSFUL; UNICODE_STRING DeviceName; PDEVICE_OBJECT DeviceObject = NULL; DbgPrint("DriverEntry()\r\n"); DriverObject->DriverUnload = DriverUnload; RtlInitUnicodeString(&DeviceName, DEVICE_NAME); //给设备对象起个名字 Status = IoCreateDevice(DriverObject, 0, &DeviceName, FILE_DEVICE_UNKNOWN, 0, FALSE, &DeviceObject); //接受设备对象 //为当前驱动对象创建设备对象 if (!NT_SUCCESS(Status)) { return Status; } IoInitializeTimer(DeviceObject, (PIO_TIMER_ROUTINE)TimerRoutine, NULL); IoStartTimer(DeviceObject);//在这之后,例程每秒一次的被调用 return STATUS_SUCCESS; } VOID DriverUnload(PDRIVER_OBJECT DriverObject) { PDEVICE_OBJECT DeviceObject = NULL; PDEVICE_OBJECT v1 = NULL; IoStopTimer(DriverObject->DeviceObject); DeviceObject = DriverObject->DeviceObject; v1 = DeviceObject; while (DeviceObject != NULL) { v1 = DeviceObject->NextDevice; IoDeleteDevice(DeviceObject); DeviceObject = v1; } DbgPrint("ByeByeDriver\r\n"); } //The driver's IoTimer routine is called at IRQL = DISPATCH_LEVEL and therefore must not contain pageable code. VOID TimerRoutine( _In_ struct DEVICE_OBJECT *DeviceObject, _In_opt_ PVOID Context ) { // 隔5秒调一次 if (__v1 < 5) { __v1++; return; } DbgPrint("TimerRoutine\r\n"); __v1 = 0; }

转载请注明原文地址: https://www.6miu.com/read-40153.html

最新回复(0)