Reputation: 305
everyone
I want to know how to debug the windows service start-up code in C.there are several questions like this but in C# but they are not what I need. So far,I can only attach to process to debug.Now I want to debug the main() function,how to do? The more detailed,the better.
Thanks so much.
My codes are below.
main function:
void main()
{
SERVICE_TABLE_ENTRY ServiceTable[2];
ServiceTable[0].lpServiceName = "MemoryStatus";
ServiceTable[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)ServiceMain; //ServiceMain
ServiceTable[1].lpServiceName = NULL;
ServiceTable[1].lpServiceProc = NULL;
StartServiceCtrlDispatcher(ServiceTable);
}
ServiceMain Function:
void ServiceMain(int argc, char** argv)
{
//...some codes....
hStatus = RegisterServiceCtrlHandler("MemoryStatus",(LPHANDLER_FUNCTION)ControlHandler);
//...some codes....
//the worker loop of a service
while(ServiceStatus.dwCurrentState == SERVICE_RUNNING)
{
char buffer[10];
sprintf(buffer,"login...");
int result = WriteToLog(buffer);
if (result)
{
ReportStatus(SERVICE_STOPPED,-1);
return;
}
Sleep(SLEEP_TIME);
}
return;
}
and control handle function:
void ControlHandler(DWORD request)
{
switch(request)
{
case SERVICE_CONTROL_STOP:
WriteToLog("Monitoring stopped.");
//...Report Status to SCM code....
return;
case SERVICE_CONTROL_SHUTDOWN:
WriteToLog("Monitoring stopped.");
//...Report Status to SCM code....
return;
default:
break;
}
//...Report Status to SCM code....
return;
}
Upvotes: 1
Views: 1296
Reputation: 305
OK,two ways: First,we can sleep the service process at the beginning of code. like this:
main()
{
sleep(10);
.....
}
and then attach to the service process, the debugger will stop at the position of breakpoint as we have 10 seconds to wait.
Second,we can use _ASSERT(FALSE)
or DebugBreak()
function at the beginning of code.
Upvotes: 0
Reputation: 3864
There are two different ways to debug a windows service from its start. Both are described here.
My preferred one consists of using a remote debugger session that starts with a service (you may use ntsd
from Windows Debugging Tool). There is a special mechanism in Windows that enables you to hijack a process based on its image name (Image File Execution Options). Below you can find a content of a .reg file that will setup this debugger for you (change the path to the one where you have Debugging tools installed):
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\svchost.exe]
"Debugger"="\"C:\\tools\\debugging\\Debugging Tools for Windows (x64)\\ntsd.exe\" -server npipe:pipe=svcpipe -noio"
Next step would be to attach to this session using user-mode debugger:
windbg -remote "npipe:pipe=svcpipe,server=localhost"
and you are ready to debug. Remember to remove the registry settings before you reboot your machine, otherwise windows will hang with a black screen :)
Upvotes: 2