Five steps to write a Windows service program in C

Source: Internet
Author: User
Tags definition functions log thread win32

Windows services are designed for applications that need to run in the background and to implement tasks that do not have user interaction. To learn the basics of this console application, C (not C + +) is the best choice. This article establishes and implements a simple service program that queries the amount of physical memory available in the system and then writes the results to a text file. Finally, you can write your own Windows services with the knowledge you have learned.

When I wrote the first NT service, I looked for an example on MSDN. There I found an article Nigel Thompson wrote: "Creating a simple Win32 Service in C + +", this article comes with a C + + example. Although this article is a good explanation for the development of the service, I still feel the lack of important information I need. I want to understand what framework to invoke, what functions to call, and when to call, but C + + doesn't make me much easier in this regard. The Object-oriented method is convenient, but it is not good for learning the basic knowledge of the service program because it encapsulates the low-level Win32 function call with class. That's why I think C is better suited to the services of writing a primary service program or implementing a simple background task. After you have a thorough understanding of the service program, write in C + + to be able to excel. When I left my old job and had to transfer my knowledge to another person, using the example I wrote in C was a very easy explanation for the NT service.

A service is a console program that runs in the background and implements tasks that do not require user interaction. The Windows NT/2000/XP operating system provides specialized support for service programs. People can use the Service Control Panel to configure the installed service program, which is the Windows 2000/xp Control Panel | "Services" in Administrative tools (or at the start | Run dialog box, enter the services.msc/s--translator note). You can configure the service to start automatically when the operating system starts, so that you do not have to manually start the service each time you reboot the system.

This article first explains how to create a service that periodically queries the available physical memory and writes the results to a text file. It then guides you through the process of building, installing, and implementing the service.

First step: main function and global definition

First, include the header file that you want. Example to invoke the Win32 function (windows.h) and Disk File writes (stdio.h):

#include <windows.h>
#include <stdio.h>

Next, define two constants:

#define SLEEP_TIME 5000
#define LOGFILE "C:\\MyServices\\memstatus.txt"

SLEEP_TIME Specifies the millisecond interval between the available memory for two consecutive queries. Use this constant when you write a service work cycle in the second step.

LOGFILE defines the path to the log file, you will use the WriteToLog function to output the results of the memory query to the file, and the WriteToLog function is defined as follows:

int WriteToLog(char* str)
{
 FILE* log;
 log = fopen(LOGFILE, "a+");
 if (log == NULL)
  return -1;
 fprintf(log, "%s\n", str);
 fclose(log);
 return 0;
}

Declare several global variables to share their values among multiple functions in a program. Also, do a forward definition of a function:

SERVICE_STATUS ServiceStatus;
SERVICE_STATUS_HANDLE hStatus;
void ServiceMain(int argc, char** argv);
void ControlHandler(DWORD request);
int InitService();

Now that the preparation is ready, you can start coding. A subset of the Service program console programs. So, you can start by defining a main function, which is the entry point of the program. For a service program, main's code is surprisingly short because it creates only the dispatch table and starts the control dispatcher.

void main()
{
 SERVICE_TABLE_ENTRY ServiceTable[2];
 ServiceTable[0].lpServiceName = "MemoryStatus";
 ServiceTable[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)ServiceMain;
 ServiceTable[1].lpServiceName = NULL;
 ServiceTable[1].lpServiceProc = NULL;
 // 启动服务的控制分派机线程
 StartServiceCtrlDispatcher(ServiceTable);
}

A program may contain several services. Each service must be listed in a dedicated dispatch table (this program defines an array of servicetable structures). Every item in this table is in the service_table_entry structure. It has two domains:

Lpservicename: Pointer to a string representing a service name; when more than one service is defined, the domain must be specified;

LPSERVICEPROC: Pointer to service main function (service entry point);

The last item in the dispatch table must be a NULL pointer to the service name and service main function field, and the text example program hosts only one service, so the definition of the service name is optional.

The Service Control Manager (Scm:services Controls manager) is a process that manages all the services of the system. When the SCM starts a service, it waits for the main thread of a process to call the StartServiceCtrlDispatcher function. Pass the dispatch table to StartServiceCtrlDispatcher. This converts the main thread of the calling process into a control dispatcher. The dispatcher launches a new thread that runs the ServiceMain function for each service in the dispatch table (in this case, only one service) dispatcher also monitors the execution of all services in the program. The dispatcher then passes the control request from the SCM to the service.

Note: If the StartServiceCtrlDispatcher function is not invoked for 30 seconds, an error is given, and in order to avoid this, we must initialize the service Dispatch table in the ServiceMain function (see the example in this article) or in a separate thread of a non-primary function. The services described in this article do not need to guard against such a situation.

After all the services in the dispatch table have been executed (for example, when the user stops them through the Services Control Panel program), or when an error occurs. The StartServiceCtrlDispatcher call returns. The main process then terminates.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.