Click here to Skip to main content
15,867,686 members
Articles / Programming Languages / C++
Article

A Windows Service Application

Rate me:
Please Sign up or sign in to vote.
4.66/5 (56 votes)
29 Nov 2006CPOL4 min read 461.4K   17.8K   212   131
A simple Windows service application to fork and monitor applications.

Introduction

Recently, I came across a situation where I needed to make an application launch automatically when the PC starts up. And the problem was that the program that I needed to launch was designed as a GUI application. The best way I could think of to make it launch automatically was to create a service based application, so that once the user logs on to the computer, the application would be executed automatically by the service and monitor the application. Then, I thought of appending more than one application into a service and run it till the service is killed or stopped.

Background

I searched a number of sites for some code that could help me create a simple Windows service application which can fork and monitor some applications, but I only found a lot of code on how to manage the current Windows services on the system. Later, I started to create my own with the help of MSDN.

Description

This is a simple Windows based services application which is created using Win32 - VC++. The usage of this application is - it will act as a Windows service which is able to fork and monitor any number of sub processes which are running under this service. The applications can be of any type like GUI, non-GUI etc.

This application will help you know about the following topics related to a service application:

  1. How to create/install a new Windows Service.
  2. How to map some applications to a particular Windows Service, and control the application by the service. (How to connect to the Control Service Manager.)
  3. How to start/run Window services.
  4. How to stop/kill Window services.
  5. How to uninstall Windows services.

Code Usage

The code is very simple, and for the most part, self-explanatory. The application executable is given the name "WinService.exe". The user has to pass some command line arguments while executing this application, through the command prompt to make use of its different features.

""ApplicationName  FeatureExtension"

Note: The default service name would be "Sundar_Service". The user can change the service name in the code and rebuild the application.

Feature Extensions

ApplicationName -i  / -I - Create / Install New service
ApplicationName - Connect to Service Control Manager
ApplicationName -s / -S - Run / Start the service
ApplicationName -k / -K - Stop / End the service
ApplicationName -u / -U - Uninstall / Kill the service from windows

Create / Install New Service

"WinService -i" or "WinService -I"

Sample Image

When you type the above line on the command prompt and press Enter, you are able to view a new service in the Windows Services window with the name "Sundar_Service".

VOID Install(char* pPath, char* pName);

The Install method creates a service object and adds it to the specified service control manager database.

SC_HANDLE schService = CreateService(
            schSCManager,     /* SCManager database      */
            pName,            /* name of service         */
            pName,            /* service name to display */
            SERVICE_ALL_ACCESS,  /* desired access       */
            SERVICE_WIN32_OWN_PROCESS|
              SERVICE_INTERACTIVE_PROCESS , /* service type  */
            SERVICE_AUTO_START,   /* start type              */
            SERVICE_ERROR_NORMAL, /* error control type      */
            pPath,                /* service's binary        */
            NULL,                 /* no load ordering group  */
            NULL,                 /* no tag identifier       */
            NULL,                 /* no dependencies         */
            NULL,                 /* LocalSystem account     */
            NULL        );        /* no password             */

Sample Image

Connect to SCM (Service Control Manager)

"WinService" or "WinService"

Sample Image

While executing the above command on the command prompt, the child processes which are mapped under the service "Sundar_Service" will get started. And these processes will be monitored by the service, so that the application can be started again if it gets killed for any reason.

VOID ExecuteSubProcess();

The "ExecuteSubProcess" method is defined with the "_beginthread" method for thread creation, which ensures the child process continues execution till the service is stopped by the user or Windows. This will also call the "StartServieCtrlDispatcher" method.

if(!StartServiceCtrlDispatcher(lpServiceStartTable))

The "StartServiceCtrlDispatcher" connects the main thread of a service process to the service control manager, which causes the thread to be the service control dispatcher thread for the calling process.

VOID WINAPI ServiceMain(DWORD dwArgc, LPTSTR *lpszArgv)

The callback functionality mapped through the lpServiceStartTable structure will register the "ServiceHandler" method to the service and update its status. Also, this will execute its child applications.

VOID WINAPI ServiceHandler(DWORD fdwControl)

The "ServieHandler" method will control service functions, like "Start", "Stop", "Pause" etc.

Note: Child applications are attached as "1.exe", "2.exe", "3.exe", and "4.exe" where the user can update or change the application. This sample application will animate an icon on the system tray of Windows.

Run / Start Service

"WinService -s" or "WinService -S"

Sample Image

When the above line is executed on the command prompt, the service "Sundar_Service" will be started.

VOID RunService(char* pPath, char* pName)

The user-defined RunService method will use the "StartService" method to start a service after getting the service control manager control handle and the service handle.

if(StartService(schService, 0, (const char**)NULL))

Sample Image

Sample Image

Stop / End Windows Service

"WinService -k" or "WinService -K"

Sample Image

This command will stop the service by sending the "SERVICE_CONTROL_STOP" control code to service the control manager using the "ControlService" method. This will lead to executing the user case functionality in the "ServiceHandler" method to stop the service.

if(ControlService(schService,SERVICE_CONTROL_STOP,&status))

Uninstall / Kill the Service from Windows

"WinService -u" or "WinService -U"

Sample Image

This command will uninstall the service from the Windows Service Manager database, after all its child processes have been stopped.

if(!DeleteService(schService))

The "DeleteService" method marks the specified service for deletion from the service control manager database.

Sample Image

Logger

Sample Image

VOID WriteLog(char* pFile, char* pMsg)

The "WriteLog" method would log all the errors and the status of the service in the application path as "Sundar_Service.Log", with the service name as the log file name.

License

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


Written By
Architect Luxoft
Germany Germany
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Answerfork/join Pin
Osberto29-Sep-12 8:25
Osberto29-Sep-12 8:25 
GeneralMy vote of 2 Pin
milindrogye3-Jul-09 20:51
milindrogye3-Jul-09 20:51 
GeneralRe: My vote of 2 Pin
mullen_kelly29-Jul-09 3:59
mullen_kelly29-Jul-09 3:59 
QuestionWhat are the parameters to CreateService() to run as NetworkService? Pin
Abhimankrishna25-Jun-09 0:36
Abhimankrishna25-Jun-09 0:36 
GeneralExcellent Work Pin
chamil madusanka24-Jun-09 23:13
chamil madusanka24-Jun-09 23:13 
Questionhow to make the service to get stopped by itself once it has performed its job? Pin
Gilly Kumar23-May-09 11:49
Gilly Kumar23-May-09 11:49 
GeneralStop service in XP User Mode Pin
uwxzzuwxzz19-Apr-09 15:56
uwxzzuwxzz19-Apr-09 15:56 
GeneralService to monitor application in PCs in network Pin
santu6-Mar-09 1:52
santu6-Mar-09 1:52 
hi,

can we use these kind of services to monitor an application in the PCs of a network?

regards,
santosh

With regards
A.Santosh

GeneralRe: Service to monitor application in PCs in network Pin
sks200810-Mar-09 9:29
sks200810-Mar-09 9:29 
GeneralNot able to start an exe as a service which exists in d://flotest/flo.exe Pin
sks20082-Mar-09 3:09
sks20082-Mar-09 3:09 
GeneralRe: Not able to start an exe as a service which exists in d://flotest/flo.exe Pin
sks20083-Mar-09 3:53
sks20083-Mar-09 3:53 
GeneralRe: Not able to start an exe as a service which exists in d://flotest/flo.exe Pin
sks20083-Mar-09 20:51
sks20083-Mar-09 20:51 
GeneralService 'Description' Pin
mullen_kelly22-Jan-09 19:37
mullen_kelly22-Jan-09 19:37 
GeneralRe: Service 'Description' Pin
Billiebub27-Jul-09 8:46
Billiebub27-Jul-09 8:46 
QuestionWhy can not work on Release mode? [modified] Pin
Jason Tian28-Sep-08 0:17
Jason Tian28-Sep-08 0:17 
QuestionCannot shutdown computer Pin
MrBwak17-Sep-08 23:46
MrBwak17-Sep-08 23:46 
QuestionStartServiceCtlDispatcher falile with eroor 1063 Pin
prashant08048215-Jul-08 3:09
prashant08048215-Jul-08 3:09 
AnswerRe: StartServiceCtlDispatcher falile with eroor 1063 Pin
MittalNeha24-Jun-10 9:56
MittalNeha24-Jun-10 9:56 
Generalservice Pin
ixeroneons10-Jul-08 1:00
ixeroneons10-Jul-08 1:00 
QuestionHow to depend Workstation and Server Services to my Service Pin
CrazyDogg18-Jun-08 2:20
CrazyDogg18-Jun-08 2:20 
AnswerRe: How to depend Workstation and Server Services to my Service Pin
CrazyDogg18-Jun-08 3:24
CrazyDogg18-Jun-08 3:24 
Generalprogram run as service Pin
statquos3-Jun-08 7:07
statquos3-Jun-08 7:07 
Generalx64 Pin
Simon Linder2-Apr-08 22:02
Simon Linder2-Apr-08 22:02 
GeneralVery Good Article Pin
VaaniPrgmr26-Feb-08 2:16
VaaniPrgmr26-Feb-08 2:16 
GeneralDevelop a smart card reader application Pin
bedabeda25-Jan-08 3:10
bedabeda25-Jan-08 3:10 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.