创建线程函数:PsCreateSystemThread
#include <ntddk.h>#include <ntstrsafe.h>#include <time.h>KSPIN_LOCK lock;ULONG test = 99;VOID UnloadDriver(PDRIVER_OBJECT pDriver){ DbgPrint("卸载成功\n");}//线程函数VOID MyThread(){ for (ULONG i = 0; i < 999;i++) { DbgPrint("I am thread,num is %d\n", test); }}VOID MyThread1(){ for (ULONG i = 0; i < 999; i++) { DbgPrint("111111,num is %d\n", test); }}NTSTATUS DriverEntry(PDRIVER_OBJECT pDriver, PUNICODE_STRING pRegPath){ NTSTATUS status = NULL; HANDLE hThread = NULL; HANDLE hThreed1 = NULL; KIRQL kIrql; //初始化自旋锁 KeInitializeSpinLock(&lock); //开启自旋锁 KeAcquireSpinLock(&lock, &kIrql); //创建线程 status = PsCreateSystemThread(&hThread, 0, NULL, NULL, NULL, MyThread, NULL); //释放锁 KeReleaseSpinLock(&lock, kIrql); status = PsCreateSystemThread(&hThreed1, 0, NULL, NULL, NULL, MyThread1, NULL); //关闭线程 ZwClose(hThread); ZwClose(hThreed1); DbgPrint("驱动加载成功\n"); pDriver->DriverUnload = UnloadDriver;}
内核线程睡眠函数KeDelayExcutionThread
将当前线程暂停指定时间,可以理解为暂停程序一定的时间
#include <ntddk.h>#include <ntstrsafe.h>#include <time.h>KSPIN_LOCK lock;ULONG testnum;VOID Thread1(){ for (ULONG i = 0; i < 66;i++) { DbgPrint("线程11111,testnum的值是:%d\n", testnum); }}VOID Thread2(){ for (ULONG i = 0; i < 66; i++) { DbgPrint("线程22222,testnum的值是:%d\n", testnum); }}VOID UnloadDriver(PDRIVER_OBJECT pDriver){ DbgPrint("卸载成功\n");}NTSTATUS DriverEntry(PDRIVER_OBJECT pDriver, PUNICODE_STRING pRegPath){ NTSTATUS status = NULL; KIRQL kIrql = NULL; HANDLE hThread1; HANDLE hThread2; LARGE_INTEGER time ; time.QuadPart = -10 * 1000 * 1000; status = PsCreateSystemThread(&hThread1,0,NULL,NULL,NULL,Thread1,NULL); status = PsCreateSystemThread(&hThread2, 0, NULL, NULL, NULL, Thread2, NULL); KeDelayExecutionThread(KernelMode, 0, &time); DbgPrint("驱动加载成功\n"); pDriver->DriverUnload = UnloadDriver;}
同步事件