Rhyous

July 9, 2010

A simple example of starting and stopping a service in windows using C++

Filed under: C/C++ — J. Abram barneck @ 8:20 am
Tags: ,

Hey all,

Here is a simple example of starting and stopping a service in C++. Just pass the service name as a parameter and the service will switch states. If stopped, it will start. If started, it will stop.

// StartStopService.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <windows.h>

int _tmain(int argc, _TCHAR* argv[])
{
	SC_HANDLE serviceDbHandle = OpenSCManager(NULL,NULL,SC_MANAGER_ALL_ACCESS);
	SC_HANDLE serviceHandle = OpenService(serviceDbHandle, argv[1], SC_MANAGER_ALL_ACCESS);

	SERVICE_STATUS_PROCESS status;
	DWORD bytesNeeded;
	QueryServiceStatusEx(serviceHandle, SC_STATUS_PROCESS_INFO,(LPBYTE) &status,sizeof(SERVICE_STATUS_PROCESS), &bytesNeeded);
	
	if (status.dwCurrentState == SERVICE_RUNNING)
	{// Stop it
		BOOL b = ControlService(serviceHandle, SERVICE_CONTROL_STOP, (LPSERVICE_STATUS) &status);
		if (b)
		{
			std::cout << "Service stopped." << std::endl;
		}
		else
		{		
			std::cout << "Service failed to stop." << std::endl;
		}
	}
	else
	{// Start it
		BOOL b = StartService(serviceHandle, NULL, NULL);
		if (b)
		{
			std::cout << "Service started." << std::endl;
		}
		else
		{		
			std::cout << "Service failed to start." << std::endl;
		}
	}
	
	CloseServiceHandle(serviceHandle);
	CloseServiceHandle(serviceDbHandle);

	return 0;
}
Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: