Thread: Basic Win32 Service Control Code

  1. #1
    Registered User The Dog's Avatar
    Join Date
    May 2002
    Location
    Cape Town
    Posts
    788

    Basic Win32 Service Control Code

    Hi

    I need to be able to do basic windows service control remotely (start, stop, restart...)

    Does anybody have any simple source for this? I'm not looking to install new or remove existing services, I merely want to either start, stop, or restart an existing service.

    I need to do this from Java, so I'm planning to implement it Win32, then use JNI to execute it from Java.

    Thanks

  2. #2
    Registered User
    Join Date
    May 2003
    Posts
    1,619
    If you're going to call an external program, there already is (on XP, probably 2000 as well) sc.exe which provides service control.

    You should be able to type "sc" at the command prompt and get a full list. You could also use "net start <servicename>", "net pause <servicename>", and "net stop <servicename" as well.

    sc is the more powerful command. It lets you query, change startup levels, etc. You can do anything in sc that you can do in the Services control panel.
    Last edited by Cat; 09-07-2006 at 04:21 AM.
    You ever try a pink golf ball, Wally? Why, the wind shear on a pink ball alone can take the head clean off a 90 pound midget at 300 yards.

  3. #3
    Registered User The Dog's Avatar
    Join Date
    May 2002
    Location
    Cape Town
    Posts
    788
    I'm currently using a tool call 'psservice.exe' by SysInternals to do service control.

    The thing is I don't want to rely on an external program... Which is why I'm looking for code to do it.

    Thanks anyway.

  4. #4
    Registered User
    Join Date
    Mar 2005
    Location
    Mountaintop, Pa
    Posts
    1,058
    Does anybody have any simple source for this?
    Please thoroughly test prior to production use.

    Code:
    #pragma comment( lib, "advapi32.lib" )      
    #include <stdio.h>
    #include <windows.h>
    #include <tchar.h>
    #include <lmerr.h>
    
    void DisplayErrorMessage(DWORD dwLastError )
    {
    	HMODULE hModule = NULL; 
    	LPSTR MessageBuffer;
    	DWORD dwBufferLength;
    	DWORD dwFormatFlags = FORMAT_MESSAGE_ALLOCATE_BUFFER |
    		FORMAT_MESSAGE_IGNORE_INSERTS |
    		FORMAT_MESSAGE_FROM_SYSTEM ;
    	if(dwLastError >= NERR_BASE && dwLastError <= MAX_NERR) {
    		hModule = LoadLibraryEx(
    			TEXT("netmsg.dll"),
    			NULL,
    			LOAD_LIBRARY_AS_DATAFILE
    			);
     		if(hModule != NULL)
    			dwFormatFlags |= FORMAT_MESSAGE_FROM_HMODULE;
    	}
    	if(dwBufferLength = FormatMessageA(
    		dwFormatFlags,
    		hModule, 
    		dwLastError,
    		MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), 
    		(LPSTR) &MessageBuffer,
    		0,
    		NULL
    		))
    	{
    		DWORD dwBytesWritten;
    		WriteFile(
    			GetStdHandle(STD_ERROR_HANDLE),
    			MessageBuffer,
    			dwBufferLength,
    			&dwBytesWritten,
    			NULL
    			);
    		LocalFree(MessageBuffer);
    	}
    	if(hModule != NULL)
    		FreeLibrary(hModule);
    }
    
    BOOL StopTheService(char* pName, char *pComputerName) 
    { 
    	DWORD dwError, dwTimeout= 0;
    	SERVICE_STATUS ss;
    	DWORD dwStartTime = GetTickCount();
    	DWORD dwBytesNeeded;
    	SC_HANDLE schSCManager = OpenSCManager( pComputerName, NULL, SC_MANAGER_ALL_ACCESS); 
    	if (schSCManager==0) 
    	{
    		dwError = GetLastError();
    		DisplayErrorMessage(dwError );
    	}
    	else
    	{
    		SC_HANDLE schService = OpenService( schSCManager, pName, SERVICE_ALL_ACCESS);
    
    		if (schService==0) 
    		{
    			dwError = GetLastError();
    			DisplayErrorMessage(dwError );
    		}
    		else
    		{
    			// check to determine if service is not already stopped
    			QueryServiceStatusEx( 
    				schService, 
    				SC_STATUS_PROCESS_INFO,
    				(LPBYTE)&ss, 
    				sizeof(SC_STATUS_PROCESS_INFO),
    				&dwBytesNeeded );
    			if ( ss.dwCurrentState == SERVICE_STOPPED ) 
    				return TRUE;
    			// stop pending, wait for it
    			while ( ss.dwCurrentState == SERVICE_STOP_PENDING ) 
    			{
    				Sleep( ss.dwWaitHint );
    				if ( !QueryServiceStatusEx( 
    					schService, 
    					SC_STATUS_PROCESS_INFO,
    					(LPBYTE)&ss, 
    					sizeof(SC_STATUS_PROCESS_INFO),
    					&dwBytesNeeded ) )
    					return FALSE;
    				if ( ss.dwCurrentState == SERVICE_STOPPED )
    					return TRUE;
    
    				if ( GetTickCount() - dwStartTime > dwTimeout )
    					return FALSE;
    			}
    			// call ControlService to stop the service
    			SERVICE_STATUS status;
    			if(ControlService(schService,SERVICE_CONTROL_STOP,&status))
    			{
    				CloseServiceHandle(schService); 
    				CloseServiceHandle(schSCManager); 
    				printf(_T("%s stopped\n"),pName);  
    				return TRUE;
    			}
    			else
    			{
    				dwError = GetLastError();
    				DisplayErrorMessage(dwError );
    			}
    			CloseServiceHandle(schService); 
    		}
    		CloseServiceHandle(schSCManager); 
    	}
    	return FALSE;
    }
    
    BOOL StartTheService(char* pName, int nArg, char** pArg, char *pComputerName) 
    { 
    	DWORD  dwError = 0l;
    	SC_HANDLE schSCManager = OpenSCManager( pComputerName, NULL, SC_MANAGER_ALL_ACCESS); 
    	if (schSCManager==0) 
    	{
    		dwError = GetLastError();
    		DisplayErrorMessage(dwError );
    	}
    	else
    	{
    		SC_HANDLE schService = OpenService( schSCManager, pName, SERVICE_ALL_ACCESS);
    		if (schService==0) 
    		{
    			dwError = GetLastError();
    			DisplayErrorMessage(dwError );
    		}
    		else
    		{
    			if(StartService(schService,nArg,(const char**)pArg))
    			{
    				CloseServiceHandle(schService); 
    				CloseServiceHandle(schSCManager); 
    				printf(_T("%s has succesfully started"), pName);
    				return TRUE;
    			}
    			else
    			{
    				dwError = GetLastError();
    				DisplayErrorMessage(dwError );
    			}
    			CloseServiceHandle(schService); 
    		}
    		CloseServiceHandle(schSCManager); 
    	}
    	return FALSE;
    }
    
    int main(int argc, char **argv)
    {
    	if(argc > 1)
    	{
    		if(strcmp(strupr(argv[1]), "START") == 0)
    			StartTheService("Messenger",0,NULL, NULL);
    		else if(strcmp(strupr(argv[1]), "STOP") == 0)
    			StopTheService("Messenger", NULL);
    		else printf("Invalid command line parms\n");       
    	}
    	else printf(" Enter START or STOP on command line\n");
    	return 0;
    }

  5. #5
    Registered User The Dog's Avatar
    Join Date
    May 2002
    Location
    Cape Town
    Posts
    788
    Thanks BobS0327.

    Will give ur code a go.

    Thanks again.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Win32 API tooltip control
    By wind_addict in forum Windows Programming
    Replies: 1
    Last Post: 05-12-2008, 06:16 AM
  2. Button handler
    By Nephiroth in forum Windows Programming
    Replies: 8
    Last Post: 03-12-2006, 06:23 AM
  3. Basic Code
    By MadCow257 in forum Game Programming
    Replies: 6
    Last Post: 03-01-2005, 05:28 PM
  4. Source Code Control Systems
    By Isometric in forum A Brief History of Cprogramming.com
    Replies: 4
    Last Post: 01-06-2002, 04:46 AM