Hey,
I have this exercise where I have PASSIVE_LEVEL job I need to perform every 10 seconds.
I can use KTIMER, But then (as far as I know) the routine will run at DISPATCH_LEVEL so I’ll have to use a work item to queue the job…
I found it was easier to just create a system thread then use KeWaitForSingleObject like this:
typedef VOID (*PERIODIC_ROUTINE)(PVOID Context);
typedef struct _PERIODIC_JOB {
PERIODIC_ROUTINE Routine;
PVOID Context;
KEVENT ExitEvent;
LARGE_INTEGER Interval;
HANDLE SystemThreadHandle;
} PERIODIC_JOB;
static
VOID
PeriodicSystemThread(
__in PVOID Context
)
{
NTSTATUS Status;
PERIODIC_JOB* Job = (PERIODIC_JOB*)Context;
while (TRUE) {
Status = KeWaitForSingleObject(
&Job->ExitEvent,
Executive,
KernelMode,
FALSE,
&Job->Interval
);
if (Status == STATUS_SUCCESS) {
//
// The thread was signaled to exit.
//
PsTerminateSystemThread(STATUS_SUCCESS);
}
if (Status == STATUS_TIMEOUT) {
Job->Routine(Job->Context);
continue;
}
KeBugCheck(0x1337);
}
}
NTSTATUS
CreatePeriodicJob(
__out PERIODIC_JOB* Job,
__in PERIODIC_ROUTINE Routine,
__in PLARGE_INTEGER Interval,
__in_opt PVOID Context
)
{
NTSTATUS Status;
OBJECT_ATTRIBUTES ThreadAttributes;
RtlZeroMemory(Job, sizeof(PERIODIC_JOB));
Job->Context = Context;
Job->Routine = Routine;
Job->Interval.QuadPart = Interval->QuadPart;
KeInitializeEvent(&Job->ExitEvent, NotificationEvent, FALSE);
InitializeObjectAttributes(&ThreadAttributes, NULL, OBJ_KERNEL_HANDLE, NULL, NULL);
return PsCreateSystemThread(
&Job->SystemThreadHandle,
0,
&ThreadAttributes,
NULL,
NULL,
PeriodicSystemThread,
Job
);
}
NTSTATUS
StopPeriodicJob(
__in PERIODIC_JOB* Job,
__in PLARGE_INTEGER Timeout
)
{
KeSetEvent(&Job->ExitEvent, IO_NO_INCREMENT, FALSE);
return ZwWaitForSingleObject(Job->SystemThreadHandle, FALSE, Timeout);
}
My question is:
- What is the general use case of KTIMER? In which case it’s useful?
- Is it bad to use a system thread like I did?
I guess that in my case it does not really matter but in case the timer is not a periodic timer it’s better to use KeSetTimer to save the overhead
of creating threads…
Sorry in advance if I’m missing something.
Thank you