Click here to Skip to main content
15,922,155 members
Please Sign up or sign in to vote.
4.50/5 (2 votes)
See more:
Hi All,
I am writing my first windows service program.The below is my service program, I am unable to run my service after installing it. When run the service, the startservice api is returning the error "The service didnot respond to the start or control request in a timely fashion" and the servicecontroldispatcher API is returning the error "the service process couldnot connect to the service controller"(this error because unable to start the service).

Some times the start service is starting properly but the servicecontroldispatcher API is returning the error "the service process couldnot connect to the service controller".

I am unable to figure what is the exact problem, could u guys please help in resolving the issue.


// MyService.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "MyService.h"
#include <winsvc.h>
#include <windows.h>


#ifdef _DEBUG
#define new DEBUG_NEW
#endif

// The one and only application object
CWinApp theApp;
using namespace std;

#define SERVICE_NAME _T("MyServiceMain")
VOID WINAPI MyServiceMain(DWORD dwArgc, LPTSTR *lpszArgv);
VOID WINAPI ServiceHandler(DWORD fdwControl);
CRITICAL_SECTION		CriticalSec;
SERVICE_TABLE_ENTRY		lpServiceStartTable[] = 
{
	{SERVICE_NAME, MyServiceMain},
	{NULL, NULL}
};
class CMyService
{
public:
	CMyService(CString strServiceName)
	{
		m_strServiceName = strServiceName;
	}

	CString					m_strServiceName;
	CString					m_strServicePath;
	SERVICE_STATUS_HANDLE   m_hServiceStatusHandle; 
	SERVICE_STATUS          m_ServiceStatus; 
	bool					CreateMyService();
	bool					DeleteMyService();
	bool					RunMyService();
	bool					StopMyService();
};

CMyService  gOMyService(SERVICE_NAME);


int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
	int nRetCode = 0;
	HMODULE hModule = ::GetModuleHandle(NULL);
	if (hModule != NULL)
	{
		// initialize MFC and print and error on failure
		if (!AfxWinInit(hModule, NULL, ::GetCommandLine(), 0))
		{
			// TODO: change error code to suit your needs
			_tprintf(_T("Fatal Error: MFC initialization failed\n"));
			nRetCode = 1;
		}
		else
		{
			if(argc == 2)
			{
				CString strCmd = argv[1];
				if(strCmd.CompareNoCase(_T("-i")) == 0)
					gOMyService.CreateMyService();
				if(strCmd.CompareNoCase(_T("-s")) == 0)
				{
					gOMyService.RunMyService();
					if(!StartServiceCtrlDispatcher(lpServiceStartTable))
					{
						long nError =  GetLastError();
						CString strError;
						LPVOID lpMsgBuf;

						FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
							NULL, nError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&lpMsgBuf, 0, NULL);
						strError = (LPTSTR)lpMsgBuf;
						MessageBox(NULL,strError,_T("Error"),MB_OK);
					}
				}
				if(strCmd.CompareNoCase(_T("-u")) == 0)
					gOMyService.DeleteMyService();
				if(strCmd.CompareNoCase(_T("-k")) == 0)
					gOMyService.StopMyService();
			}
			//
			//gOMyService.RunMyService();
			//gOMyService.DeleteMyService();
			
		}
	}
	else
	{
		// TODO: change error code to suit your needs
		_tprintf(_T("Fatal Error: GetModuleHandle failed\n"));
		nRetCode = 1;
	}
	return nRetCode;
}

/**
	- Main Function of the service main
*/
VOID WINAPI MyServiceMain(DWORD dwArgc, LPTSTR *lpszArgv)
{
	MessageBox(NULL,_T("test"),_T("Error"),MB_OK);
	DWORD   status = 0; 
    DWORD   specificError = 0xfffffff; 
 
	gOMyService.m_ServiceStatus.dwServiceType        = SERVICE_WIN32; 
    gOMyService.m_ServiceStatus.dwCurrentState       = SERVICE_RUNNING; 
    gOMyService.m_ServiceStatus.dwControlsAccepted   = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN | SERVICE_ACCEPT_PAUSE_CONTINUE; 
    gOMyService.m_ServiceStatus.dwWin32ExitCode      = 0; 
    gOMyService.m_ServiceStatus.dwServiceSpecificExitCode = 0; 
    gOMyService.m_ServiceStatus.dwCheckPoint         = 0; 
    gOMyService.m_ServiceStatus.dwWaitHint           = 0; 
 
	gOMyService.m_hServiceStatusHandle = RegisterServiceCtrlHandler(gOMyService.m_strServiceName, ServiceHandler); 
    if (!gOMyService.m_hServiceStatusHandle) 
    {
		long nError =  GetLastError();
		CString strError;
		LPVOID lpMsgBuf;

		FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
			NULL, nError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&lpMsgBuf, 0, NULL);
		strError = (LPTSTR)lpMsgBuf;
		MessageBox(NULL,strError,_T("Error"),MB_OK);
        return; 
    } 
 
    // Initialization complete - report running status 
    gOMyService.m_ServiceStatus.dwCurrentState       = SERVICE_RUNNING; 
    gOMyService.m_ServiceStatus.dwCheckPoint         = 0; 
    gOMyService.m_ServiceStatus.dwWaitHint           = 0;  
    if(!SetServiceStatus(gOMyService.m_hServiceStatusHandle, &gOMyService.m_ServiceStatus)) 
    { 
		long nError = GetLastError();
		char pTemp[121];
		sprintf(pTemp, "SetServiceStatus failed, error code = %d\n", nError);
    } 
	if(!StartServiceCtrlDispatcher(lpServiceStartTable))
	{
		long nError =  GetLastError();
		CString strError;
		LPVOID lpMsgBuf;

		FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
			NULL, nError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&lpMsgBuf, 0, NULL);
		strError = (LPTSTR)lpMsgBuf;
		MessageBox(NULL,strError,_T("Error"),MB_OK);
	}
}
VOID WINAPI ServiceHandler(DWORD fdwControl)
{
	switch(fdwControl) 
	{
		case SERVICE_CONTROL_STOP:
		case SERVICE_CONTROL_SHUTDOWN:
			{
				gOMyService.m_ServiceStatus.dwWin32ExitCode = 0; 
				gOMyService.m_ServiceStatus.dwCurrentState  = SERVICE_STOPPED; 
				gOMyService.m_ServiceStatus.dwCheckPoint    = 0; 
				gOMyService.m_ServiceStatus.dwWaitHint      = 0;
				::DeleteCriticalSection(&CriticalSec);
			}
			break; 
		case SERVICE_CONTROL_PAUSE:
			gOMyService.m_ServiceStatus.dwCurrentState = SERVICE_PAUSED; 
			break;
		case SERVICE_CONTROL_CONTINUE:
			gOMyService.m_ServiceStatus.dwCurrentState = SERVICE_RUNNING; 
			break;
		case SERVICE_CONTROL_INTERROGATE:
			break;
		default:
			{
			}
		
	};
	if (!SetServiceStatus(gOMyService.m_hServiceStatusHandle,  &gOMyService.m_ServiceStatus)) 
	{ 
		long nError = GetLastError();
		char pTemp[121];
		sprintf(pTemp, "SetServiceStatus failed, error code = %d\n", nError);
		
    }
}


bool CMyService::CreateMyService()
{
	bool bRet = false;
	SC_HANDLE hServiceMngr = NULL;
	TCHAR szPath[MAX_PATH];
    if( !GetModuleFileName( NULL, szPath, MAX_PATH ) )
    {
        //printf("Cannot install service (%d)\n", GetLastError());
        return bRet;
    }
	hServiceMngr = OpenSCManager( NULL, NULL, SC_MANAGER_ALL_ACCESS); 
	if (hServiceMngr) 
	{
		SC_HANDLE hService = ::CreateServiceW
		( 
			hServiceMngr,	/* SCManager database      */ 
			m_strServiceName,			/* name of service         */ 
			m_strServiceName,			/* service name to display */ 
			SERVICE_ALL_ACCESS,        /* desired access          */ 
			SERVICE_WIN32_OWN_PROCESS , /* service type            */ 
			SERVICE_AUTO_START,      /* start type              */ 
			SERVICE_ERROR_NORMAL,      /* error control type      */ 
			szPath,			/* service's binary        */ 
			NULL,                      /* no load ordering group  */ 
			NULL,                      /* no tag identifier       */ 
			NULL,                      /* no dependencies         */ 
			NULL,                      /* LocalSystem account     */ 
			NULL
		);/* no password             */ 
		
		char pTemp[121];
		if (hService) 
		{
			char pTemp[121];
			sprintf(pTemp, "Service %s installed\n", m_strServiceName);
			CloseServiceHandle(hService); 
			bRet = true;
		}
		else
		{
			long nError =  GetLastError();
			CString strError;
			LPVOID lpMsgBuf;
	
			FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
						  NULL, nError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&lpMsgBuf, 0, NULL);
			strError = (LPTSTR)lpMsgBuf;
			MessageBox(NULL,strError,_T("Error"),MB_OK);
		}
		CloseServiceHandle(hServiceMngr);
	}	
	else
	{
		long nError = GetLastError();
		char pTemp[121];
		sprintf(pTemp, "OpenSCManager failed, error code = %d\n", nError);
	}
	
	return bRet;
}

bool CMyService::RunMyService()
{
	// run service with given name
	SC_HANDLE hSCMngr = OpenSCManager( NULL, NULL, SC_MANAGER_ALL_ACCESS); 
	
	if(hSCMngr)
	{
		// open the service
		SC_HANDLE hServiceHandle = OpenService( hSCMngr, m_strServiceName, SERVICE_ALL_ACCESS);
		
		if(hServiceHandle)
		{
			// call StartService to run the service
			if(StartService(hServiceHandle, 0, NULL))
			{
				CloseServiceHandle(hServiceHandle); 
				CloseServiceHandle(hSCMngr); 
				return TRUE;
			}
			else
			{
				long nError =  GetLastError();
				CString strError;
				LPVOID lpMsgBuf;

				FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
					NULL, nError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&lpMsgBuf, 0, NULL);
				strError = (LPTSTR)lpMsgBuf;
				MessageBox(NULL,strError,_T("Error"),MB_OK);
			}
			CloseServiceHandle(hServiceHandle); 
		}
		else
		{
			long nError =  GetLastError();
			CString strError;
			LPVOID lpMsgBuf;

			FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
				NULL, nError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&lpMsgBuf, 0, NULL);
			strError = (LPTSTR)lpMsgBuf;
			MessageBox(NULL,strError,_T("Error"),MB_OK);
		}
		CloseServiceHandle(hSCMngr); 
	}
	else
	{
		long nError =  GetLastError();
		CString strError;
		LPVOID lpMsgBuf;

		FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
			NULL, nError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&lpMsgBuf, 0, NULL);
		strError = (LPTSTR)lpMsgBuf;
		MessageBox(NULL,strError,_T("Error"),MB_OK);
	}
	return FALSE;
}
/**
	-	Function to stop the service
*/
bool	CMyService::StopMyService()
{
	// kill service with given name
	SC_HANDLE hSCMmngr = OpenSCManager( NULL, NULL, SC_MANAGER_ALL_ACCESS); 
	
	
	if(hSCMmngr)
	{
		// open the service
		SC_HANDLE hServiceHandle = OpenService( hSCMmngr, m_strServiceName, SERVICE_ALL_ACCESS);
		
		
		if(hServiceHandle)
		{
			// call ControlService to kill the given service
			SERVICE_STATUS status;
			if(ControlService(hServiceHandle,SERVICE_CONTROL_STOP,&status))
			{
				CloseServiceHandle(hServiceHandle); 
				CloseServiceHandle(hSCMmngr); 
				return TRUE;
			}
			else
			{
				long nError = GetLastError();
				char pTemp[121];
				sprintf(pTemp, "ControlService failed, error code = %d\n", nError);
			}
			CloseServiceHandle(hServiceHandle); 
		}
		else
		{
			long nError = GetLastError();
			char pTemp[121];
			sprintf(pTemp, "OpenService failed, error code = %d\n", nError);
		}
		CloseServiceHandle(hSCMmngr); 
	}
	else
	{
		long nError = GetLastError();
		char pTemp[121];
		sprintf(pTemp, "OpenSCManager failed, error code = %d\n", nError);
	}
	return FALSE;
}
/**
	- Function to delete the service
*/
bool CMyService::DeleteMyService()
{
	bool	bRet=false;
	SC_HANDLE hServiceMngr = OpenSCManager( NULL, NULL, SC_MANAGER_ALL_ACCESS); 
	
	if(hServiceMngr)
	{
		SC_HANDLE hServiceHandle = OpenService( hServiceMngr, m_strServiceName, SERVICE_ALL_ACCESS);
		if(hServiceHandle)
		{
			if(!DeleteService(hServiceHandle)) 
			{
				//Failed to delete the service
				long nError =  GetLastError();
				CString strError;
				LPVOID lpMsgBuf;

				FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
					NULL, nError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&lpMsgBuf, 0, NULL);
				strError = (LPTSTR)lpMsgBuf;
				MessageBox(NULL,strError,_T("Error"),MB_OK);
			}
			CloseServiceHandle(hServiceHandle); 
		}
		CloseServiceHandle(hServiceMngr);	
	}
	else
	{
		long nError =  GetLastError();
		CString strError;
		LPVOID lpMsgBuf;

		FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
			NULL, nError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&lpMsgBuf, 0, NULL);
		strError = (LPTSTR)lpMsgBuf;
		MessageBox(NULL,strError,_T("Error"),MB_OK);
	}
	return  bRet;
}</windows.h></winsvc.h>
Posted
Updated 13-Jun-11 0:39am
v2
Comments
Niklas L 13-Jun-11 8:04am    
Add a ::DebugBreak() and attach the debugger to see what happens.
g_satish 13-Jun-11 9:29am    
The result is the same..startservice API is failing
Niklas L 13-Jun-11 10:45am    
Have you tried starting it from the Services GUI? Who wrote the service you‘re trying to start? Do you have access to the source? Checking the Event Log is a good idea.

1 solution

1) Try running it as administrator.

2) Try running the service itself in the foreground rather than as a service (just double click on the exe). If the service is missing a DLL or something, you'll get an error message on the screen that makes sense. When you run it as a service that error message gets swallowed and all you see is that the service failed to start.

NOTE: These might sound like off the cuff solutions, but I have a shipping product that includes a windows service and occasionally a customer will have exactly the problem you are describing. The problem is always solved by either (1) or (2) above.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900