📄 winservice.c
字号:
__leave;
}
/* * Open registered service */
hService = OpenService(hSCManager,
lpszServiceName,
SERVICE_ALL_ACCESS);
if (hService == NULL)
{
_stprintf(MsgErrorString, "%s %s", _T("Can't open service"), lpszServiceName);
MessageBox(NULL,
MsgErrorString,
g_szAppName,
MB_ICONHAND);
__leave;
}
/* * Query service status */
/* * If running stop before deleting */
if (QueryServiceStatus(hService, &sStatus))
{
if (sStatus.dwCurrentState == SERVICE_RUNNING ||
sStatus.dwCurrentState == SERVICE_PAUSED)
{
/* * Shutdown the service */
ControlService(hService, SERVICE_CONTROL_STOP, &sStatus);
}
};
/* * Delete the service */
if (DeleteService(hService) == FALSE)
{
_stprintf(MsgErrorString, "%s %s", _T("Can't delete service"), lpszServiceName);
MessageBox(NULL,
MsgErrorString,
g_szAppName,
MB_ICONHAND);
/* * Log message to eventlog */
WriteToEventLog(EVENTLOG_INFORMATION_TYPE, MsgErrorString);
__leave;
}
/* * Service deleted successfully */
_stprintf(MsgErrorString, "%s %s", lpszServiceName, _T("- Service deleted"));
/* * Log message to eventlog */
WriteToEventLog(EVENTLOG_INFORMATION_TYPE, MsgErrorString);
/* * Delete registry entires for EventLog */
_tcscpy(szRegKey, szRegAppLogKey);
_tcscat(szRegKey, lpszServiceName);
RegDeleteKey(HKEY_LOCAL_MACHINE, szRegKey);
MessageBox(NULL,
MsgErrorString,
g_szAppName,
MB_ICONINFORMATION);
}
/* * Delete the handles */
__finally
{
if (hService) CloseServiceHandle(hService);
if (hSCManager) CloseServiceHandle(hSCManager);
}
}
/* *
* * To write message to Windows Event log
* * Input - Event Type, Message string
* *
*/
VOID WriteToEventLog(WORD wType, LPCTSTR pszFormat,...)
{
TCHAR szMessage[512];
LPTSTR LogStr[1];
va_list ArgList;
HANDLE hEventSource = NULL;
va_start(ArgList, pszFormat);
_vstprintf(szMessage, pszFormat, ArgList);
va_end(ArgList);
LogStr[0] = szMessage;
hEventSource = RegisterEventSource(NULL, g_szAppName);
if (hEventSource == NULL) return;
ReportEvent(hEventSource,
wType,
0,
DISPLAY_MSG, /* To Just output the text to event log */
NULL,
1,
0,
LogStr,
NULL);
DeregisterEventSource(hEventSource);
if (!g_fRunningAsService)
{
/* * We are running in command mode, output the string */
_putts(szMessage);
}
}
/* *
* * Handle command-line arguments from the user.
* * Serivce related options are:
* * -register - registers the service
* * -unregister - unregisters the service
* * -service - run as serivce
* * other command-line arguments are unaltered/ignored.
* * They should supplied as first arguments(other wise they will be ignored
* * Return: Type indicating the option specified
*/
INT ParseCmdLineForServiceOption(int argc, TCHAR * argv[])
{
int nReturn = RUN_AS_CONSOLE; /* Defualted to run as console */
if (argc >= 2)
{
/* * second argument present */
if (lstrcmpi(_T("-register"), argv[1]) == 0)
{
nReturn = REGISTER_SERVICE;
}
else if (lstrcmpi(_T("-unregister"), argv[1]) == 0)
{
nReturn = UN_REGISTER_SERVICE;
}
else if (lstrcmpi(_T("-service"), argv[1]) == 0)
{
nReturn = RUN_AS_SERVICE;
}
}
return nReturn;
}
/* *
* * To Display an error message describing the last system error
* * message, along with a title passed as a parameter.
*/
VOID DisplayError(LPCTSTR pszTitle)
{
LPVOID pErrorMsg;
/* * Build Error String */
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) & pErrorMsg,
0,
NULL);
if (g_fRunningAsService != FALSE)
{
WriteToEventLog(EVENTLOG_ERROR_TYPE, pErrorMsg);
}
else
{
MessageBox(NULL, pErrorMsg, pszTitle, MB_ICONHAND);
}
LocalFree(pErrorMsg);
}
/* *
* * To update current service status
* * Sends the current service status to the SCM. Also updates
* * the global service status structure.
*/
static BOOLUpdateServiceStatus(DWORD dwStatus,
DWORD dwErrorCode,
DWORD dwWaitHint)
{
BOOL fReturn = FALSE;
DWORD static dwCheckpoint = 1;
DWORD dwControls = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_PAUSE_CONTINUE;
if (g_fRunningAsService == FALSE) return FALSE;
ZeroMemory(&ServiceStatus, sizeof(ServiceStatus));
ServiceStatus.dwServiceType = SERVICE_WIN32;
ServiceStatus.dwCurrentState = dwStatus;
ServiceStatus.dwWaitHint = dwWaitHint;
if (dwErrorCode)
{
ServiceStatus.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR;
ServiceStatus.dwServiceSpecificExitCode = dwErrorCode;
}
/* * special cases that depend on the new state */
switch (dwStatus)
{
case SERVICE_START_PENDING:
dwControls = 0;
break;
case SERVICE_RUNNING:
case SERVICE_STOPPED:
dwCheckpoint = 0;
break;
}
ServiceStatus.dwCheckPoint = dwCheckpoint++;
ServiceStatus.dwControlsAccepted = dwControls;
return ReportCurrentServiceStatus();
}
/* *
* * Reports current Service status to SCM
*/
static BOOLReportCurrentServiceStatus()
{
return SetServiceStatus(hServiceStatus, &ServiceStatus);
}
/* *
* * The ServiceMain function to start service.
*/
VOID WINAPI ServiceMain(DWORD argc, LPTSTR argv[])
{
SECURITY_ATTRIBUTES SecurityAttributes;
DWORD dwThreadId;
/* * Input Arguments to function startup */
DWORD ArgCount = 0;
LPTSTR * ArgArray = NULL;
TCHAR szRegKey[512];
TCHAR szValue[128];
DWORD nSize;
HKEY hParamKey = NULL; /* To read startup parameters */
DWORD TotalParams = 0;
DWORD i;
InputParams ThreadInputParams;
/* * Build the Input parameters to pass to thread */
/* * SCM sends Service Name as first arg, increment to point
* * arguments user specified while starting contorl agent
*/
/* * Read registry parameter */
/* * Initialize count to 1 */
ArgCount = 1;
/* * Create Registry Key path */
_stprintf(szRegKey, "%s%s\\%s", _T("SYSTEM\\CurrentControlSet\\Services\\"), g_szAppName, "Parameters");
if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, szRegKey, 0, KEY_ALL_ACCESS, &hParamKey) == ERROR_SUCCESS)
{
/* * Read startup Configuration information */
/* * Find number of subkeys inside parameters */
if (RegQueryInfoKey (hParamKey, NULL, NULL, 0, NULL, NULL, NULL, &TotalParams, NULL, NULL, NULL, NULL) == ERROR_SUCCESS)
{
if (TotalParams != 0)
{
ArgCount += TotalParams;
/* * Allocate memory to hold strings */
ArgArray = (LPTSTR *) malloc(sizeof(LPTSTR) * ArgCount);
/* * Copy first argument */
ArgArray[0] = _tcsdup(argv[0]);
for (i = 1; i <= TotalParams; i++)
{
/* * Create Subkey value name */
_stprintf(szRegKey, "%s%d", "Param", i);
/* * Set size */
nSize = 128;
RegQueryValueEx(hParamKey, szRegKey, 0, NULL, (LPBYTE) & szValue, &nSize);
ArgArray[i] = _tcsdup(szValue);
}
}
}
RegCloseKey(hParamKey);
}
if (ArgCount == 1)
{
/* * No statup agrs are given */
ThreadInputParams.Argc = argc;
ThreadInputParams.Argv = argv;
}
else
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -