HSCManager = OpenSCManager(
NULL, //Local Computer
NULL, //ServicesActive database
SC_MANAGER_ALL_ACCESS);//full access rights
if (HSCManager)
{
//Create Service
Hservice = CreateService(
HSCManager, //SCM database
MONDISK_SERVICE_NAME, //name of service
MONDISK_SERVICE_NAME, //service name to display
SERVICE_ALL_ACCESS, //desired access
SERVICE_KERNEL_DRIVER, //service type
SERVICE_DEMAND_START, //start type
SERVICE_ERROR_IGNORE, //error control type
servicePath, //path to service's binary
NULL, //no load ordering group
NULL, // no tag identifier
NULL, // no dependencies
NULL, // LocalSystem account
NULL); // no password
if (Hservice == NULL)
{
errorCode= GetLastError();
printf("Install service :%d\n",errorCode);
CloseServiceHandle(HSCManager);
return FALSE;
}
else{
printf("[InstallMyService] install service succeed\n");
printf("[InstallMyService] start this service");
if (!QueryServiceStatusEx(
Hservice,
SC_STATUS_PROCESS_INFO,
(UCHAR *)&serviceInfo,
sizeof(serviceInfo),
&bytesNeeded)){
errorCode = GetLastError();
printf("Query service status failed %d\n",errorCode);
}
if (serviceInfo.dwCurrentState != SERVICE_RUNNING)
{
//service has not been started,so try to start service
if (!StartService(Hservice,0,NULL)){
errorCode = GetLastError();
printf("start service failed %d\n",errorCode);
return FALSE;
}
if (!HSCManager)
{
printf("[UnInstallDriver] SCMManager handle is not available\n");
//Get a handle to the SCM database
HSCManager = OpenSCManager(
NULL,
NULL,
SC_MANAGER_ALL_ACCESS);
if (!HSCManager)
{
errorCode = GetLastError();
printf("open SCManager handle failed:%d\n",errorCode);
return FALSE;
}
}else{
//get a handle to the service
Hservice = OpenService(
HSCManager,
MONDISK_SERVICE_NAME,
SERVICE_ALL_ACCESS);
if (!Hservice)
{
errorCode = GetLastError();
printf("[UnInstallDriver] Open Service from SCM failed:%d\n",errorCode);
CloseServiceHandle(HSCManager);
return FALSE;
}
if( !ControlService( Hservice, SERVICE_CONTROL_STOP, &ServiceStatus ) )
{
errorCode = GetLastError();
printf("[StopDriver]ControlService failed:%d\n",errorCode);
return FALSE;
}
//delete the service
//DeleteMyService:
printf("[uninstallMyService]Deleting service\n");
if (!DeleteService(Hservice))
{
if (GetLastError() == ERROR_SERVICE_MARKED_FOR_DELETE)
{
printf("[UnInstallDriver]ERROR_SERVICE_MARKED_FOR_DELETE\n");
CloseServiceHandle(Hservice);
}
return FALSE;
}else
printf("[UnInstallDriver]Service deleted successfully\n");
}