知/Delphi

특정 서비스가 실행되는지 여부 체크하기

채수욱 2009. 10. 5. 13:16
{
- Torry에서 퍼왔습니다. -

서버의 특정 서비스가 실행되는지 여부를 체크할 수 있습니다.

현재 이 프로그램에서는 MS SQL SERVER가 정상적으로 시작 되었는지를 체크 합니다.
}

unit Unit1;

interface

uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, WinSvc,
StdCtrls, ExtCtrls;

type
TForm1 = class(TForm)
Memo1: TMemo;
Timer1: TTimer;
Panel1: TPanel;
procedure Timer1Timer(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

{$R *.DFM}

function ServiceGetStatus(sMachine, sService: PChar): DWORD;
{******************************************}
{*** Parameters: ***}
{*** sService: specifies the name of the service to open
{*** sMachine: specifies the name of the target computer
{*** ***}
{*** Return Values: ***}
{*** -1 = Error opening service ***}
{*** 1 = SERVICE_STOPPED ***}
{*** 2 = SERVICE_START_PENDING ***}
{*** 3 = SERVICE_STOP_PENDING ***}
{*** 4 = SERVICE_RUNNING ***}
{*** 5 = SERVICE_CONTINUE_PENDING ***}
{*** 6 = SERVICE_PAUSE_PENDING ***}
{*** 7 = SERVICE_PAUSED ***}
{******************************************}
var
SCManHandle, SvcHandle: SC_Handle;
SS: TServiceStatus;
dwStat: DWORD;
begin
dwStat := 0;
// Open service manager handle.
SCManHandle := OpenSCManager(sMachine, nil, SC_MANAGER_CONNECT);
if (SCManHandle > 0) then begin
SvcHandle := OpenService(SCManHandle, sService, SERVICE_QUERY_STATUS);
// if Service installed
if (SvcHandle > 0) then begin
// SS structure holds the service status (TServiceStatus);
if (QueryServiceStatus(SvcHandle, SS)) then
dwStat := ss.dwCurrentState;
CloseServiceHandle(SvcHandle);
end;
CloseServiceHandle(SCManHandle);
end;
Result := dwStat;
end;

function ServiceRunning(sMachine, sService: PChar): Boolean;
begin
Result := SERVICE_RUNNING = ServiceGetStatus(sMachine, sService);
end;

// Check if Eventlog Service is running
procedure TForm1.Timer1Timer(Sender: TObject);
begin
if ServiceRunning(nil, 'MSSQLSERVER') then
Memo1.Lines.Insert(0,'Running')
else
Memo1.Lines.Insert(0,'Not Running');

Panel1.Caption := ' Memo Lines : '+FormatFloat(',0',Memo1.Lines.Count);
end;

{
Windows 2000 and earlier: All processes are granted the SC_MANAGER_CONNECT,
SC_MANAGER_ENUMERATE_SERVICE, and SC_MANAGER_QUERY_LOCK_STATUS access rights.

Windows XP: only authenticated users are granted the SC_MANAGER_CONNECT,
SC_MANAGER_ENUMERATE_SERVICE,
and SC_MANAGER_QUERY_LOCK_STATUS access rights.
}

{
Do not use the service display name (as displayed in the services
control panel applet.) You must use the real service name, as
referenced in the registry under
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services
}

procedure TForm1.FormShow(Sender: TObject);
begin
Memo1.Lines.Clear;
end;

end.

 

출처 : 델마당 이시종 님 글