Cleanup過程進行的工作都是很顯然的,不用過多解釋。唯一的奧妙在於將內存映射到用戶空間和還原操作是借助於MmUnmapLockedPages函數實現的,應該在進程定義的地址上下文中進行,這是很自然的。
以上就是整個的驅動程序,利用內核計時器大約每1秒鐘讀取一次系統時間並寫入到共享內存中供用戶程序讀取。下面我們來看看用戶程序。
代碼:unit main;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls;
type
TForm1 = class(TForm)
Timer1: TTimer;
Label1: TLabel;
procedure FormActivate(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
uses
WinSvc, nt_status, macros;
const
_Delete = $10000;
var
hDevice: THANDLE;
pSharedMemory: PFILETIME;
hSCManager: THANDLE;
hService: THANDLE;
{$R *.dfm}
procedure TForm1.FormActivate(Sender: TObject);
var
acModulePath: string;
dwBytesReturned: DWORD;
lpTemp: PChar;
IOCTL_GIVE_ME_YOUR_MEMORY: DWORD;
begin
IOCTL_GIVE_ME_YOUR_MEMORY := CTL_CODE(FILE_DEVICE_UNKNOWN,
$800, METHOD_BUFFERED,
FILE_READ_ACCESS);
hSCManager := OpenSCManager(nil, nil, SC_MANAGER_ALL_ACCESS);
if hSCManager <> 0 then
begin
acModulePath := GetCurrentDir + + ExtractFileName(SharingMemory.sys);
hService := CreateService(hSCManager, SharingMemory,
Another way how to share memory,
SERVICE_START or SERVICE_STOP or _Delete,
SERVICE_KERNEL_DRIVER,
SERVICE_DEMAND_START,
SERVICE_ERROR_IGNORE,
PChar(acModulePath),
nil, nil, nil, nil, nil);
if hService <> 0 then
begin
if StartService(hService, 0, lpTemp) then
begin;
hDevice := CreateFile(PChar(\.SharingMemory),
GENERIC_READ, 0,
nil, OPEN_EXISTING, 0, 0);
if hDevice <> INVALID_HANDLE_VALUE then
begin
if DeviceIoControl(hDevice, IOCTL_GIVE_ME_YOUR_MEMORY,
nil, 0, @pSharedMemory,
sizeof(PVOID),
dwBytesReturned,
nil) then
begin
if dwbytesReturned = sizeof(pSharedMemory) then
begin
Timer1.Enabled := true; {激活用戶端計時器,每隔1秒讀取一次共享內存}
end;
end else
begin
ShowMessage(Cant send control code to device.);
end;
end else
begin
ShowMessage(Device is not present.);
end;
end else
begin
ShowMessage(Cant start driver.);
end;
end else
begin
ShowMessage(Cant register driver.);
end;
&