Joe1sn's Cabinet

windows内核驱动 7-进程同步

日常复习操作系统

同步方式

  • 自旋锁,之前讲过了
  • 信号量
  • 互斥体
  • 事件同步

事件同步

基于事件的同步,理解原理比写代码更重要

image-20240321102341054

感觉上和R3的使用差不多

  • KeInitializeEvent(&kEvent, NotificationEvent, FALSE);

    NotificationEvent:通知事件,手动处理,一般只用一次

    SynchronizationEvent:同步事件,KeWaitForSingleObject等待通过,及不需要KeResetEvent,系统自动设置为未激发态

  • 如果在R3使用Event传递Handle到R0,由于HANDLE不是全局,所以得ObReferenceObj

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
VOID KThreadB(PVOID context) {
LARGE_INTEGER sleeptime = { 0 };
PKEVENT pevent = (PKEVENT)context;
sleeptime.QuadPart = -100 * 10 * 1000 * 3;
while (1)
{
KeDelayExecutionThread(KernelMode, FALSE, &sleeptime);
DbgPrint("Traggering envet\n");
KeSetEvent(pevent, IO_NO_INCREMENT, FALSE);
}
PsTerminateSystemThread(0);
}

VOID KThreadA(PVOID context) {
UNREFERENCED_PARAMETER(context);
KeInitializeEvent(&kEvent, NotificationEvent, FALSE);
HANDLE hThread = NULL;
NTSTATUS status = PsCreateSystemThread(&hThread, 0, NULL, NULL, NULL, KThreadB, (PVOID)&kEvent);
if (!NT_SUCCESS(status)) {
DbgPrint("Create System Thread Failed\n");
}
ZwClose(hThread);
while (1)
{
KeWaitForSingleObject(&kEvent, Executive, KernelMode, FALSE, NULL);
DbgPrint("Event Just Triggered\n");
KeResetEvent(&kEvent);
}
PsTerminateSystemThread(0);
}

image-20240321104634499