I'm writing a C application which creates a Windows service. I'd like to check if the service is installed before trying to call the installation function, but I can't manage to find how to check it.
I've written the code above to try :
DWORD InstallMyService()
{
char strDir[1024 + 1];
SC_HANDLE schSCManager;
SC_HANDLE schService;
LPCTSTR lpszBinaryPathName;
if (GetCurrentDirectory(1024, strDir) == 0)
{
aff_error("GetCurrentDirectory");
return FALSE;
}
strcat(strDir, "\\"MY_SERVICE_BIN_NAME);
if ((schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS)) == NULL)
{
printf("Error OpenSCManager : %d\n", GetLastError());
return FALSE;
}
lpszBinaryPathName = strDir;
schService = CreateService(schSCManager, MY_SERVICE_NAME, MY_SERVICE_DESCRIPTOR,
SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
lpszBinaryPathName, NULL, NULL, NULL, NULL, NULL);
if (schService == NULL)
{
printf("Error CreateService : %d\n", GetLastError());
return FALSE;
}
CloseServiceHandle(schService);
return TRUE;
}
But this code does not detect if the service is still existing or not. Do someone have an idea of which function to call ? I found many posts talking about this, but not in C, only in C# or VB.
Thank you.
If you need a yes / no answer whether a service is installed or note, use the following function:
A possibility would be to always attempt to
CreateService()
and if failure queryGetLastError()
and check if it is equal toERROR_SERVICE_EXISTS
:This would require a slight change to your code from having two functions
InstallService()
andCheckService()
to having one function (for example)EnsureServiceInstalled()
.Or, you could use the
OpenService()
function, which will fail withGetLastError()
code ofERROR_SERVICE_DOES_NOT_EXIST
:Try using QueryServiceStatusEx
See example here