The principle and implementation of Windows service programs (services are divided into WIN32 services and system services)

Source: Internet
Author: User

Today to tell you how to do a service program ... I wanted to talk about it in detail, but it was very tiring to write. A lot

The place is not detailed ... But I added a note to the code ... If there's something you don't understand, check out MSDN ... Cheap

Environment, vc++6.0 ... the code has two paragraphs, one for the service program. Another section is the installation of the service program ... This program

The function is to start the drip sound .... After successful installation, start your own point ... The next time the power-up is automatically started ....

The implementation of Load.exe is relatively simple, originally wanted to get a compilation version ... But really tired ... Even if it is. Here a service

The basic framework of the service is complete ... The rest is just adding your own feature code ...

How to install:: I built a folder named Sysnap in the C-drive. There are two exe inside. One is sv.exe another

One is Svload.exe then cmd to this folder, enter Svload.exe to install the service successfully ... After booting, there is a

A service process Sv.exe ... So we have a service called Sysnap. In the registration table you can find the relevant

Information.... Of course you can change the service name to your own .... Svload.exe's code is simple: I didn't bet.

Release,,,, if you need my reply note again. I'm tired now.

The basic framework of a service

1 Perceptual knowledge what is Service

2 Installing services with INF files

3 Some basic theoretical knowledge about services

41 Creation processes and basic components of a service

5 details of each basic function.

6 Some of the data structures and API descriptions used

7 Start Our first service, complete code

8 Run our service, complete code

1 Perceptual knowledge what is Service

In the Run box, enter Services.msc. See, these are Windows services. There are some windows own, some are third-party services, such as our anti-virus software most of them have a service

What's the use of the service,.. Let's look at the definition of the service first.

Service: is an application type that runs in the background.

It can be seen that if we put the program into service, we could still run ... If it is set to manual, then after the boot of our service program will automatically run up ... So a lot of Trojans are getting into service startup, which is more than what run in the registration table

It's going to be more discreet.

The system has two kinds of services. A kind of call Win32 service, he runs in the user state, the corresponding image file is. EXE or. DLL: What we're talking about here is Win32 service.

Another kind of call system service, it runs in the kernel state, the corresponding image file is. SYS is also the driver: In fact, these two concepts do not need to subdivide it now. Apart from the different operating states, there is also a difference, that is, in the registry in addition to the hkey_local_machine/syste/currentcontrolset/services under a service name, system services also has a device hard-health HKEY_ Local_machinesystem/currentcontrolset/enum Sub-key, because it is the driver, in the removal of some kernel Trojan. This build is not deleted by default because system permissions are required. But right-----add--------you can do it.

2 Installing services with INF files

Now we're going to use. INF file to turn our EXE program into a service. Run with the power on, this EXE file I was in the bar a few days ago which small program, is still the output of the computer user name ... Build a folder in the C drive, named Sysnap. Put our program Sysnap.exe in.

Open the Notebook, the following code is written in, Save as Sysnap.inf

[Version]

Signature= "$WINDOWS nt$"

[Defaultinstall.services]

Addservice=sysnap,,my_addservice_name

[My_addservice_name]

Displayname=sysnap

description= Display Computer User name

servicetype=0x10

starttype=2

Errorcontrol=0

Servicebinary=c:/sysnap/sysnap.exe

Explain

1. ServiceType Service type: 0x10 service for standalone processes, 0x20 for shared processes (e.g. Svchost)

2. StartType Startup type: 0 load on system boot, 1 OS initialization, 2 auto start by SCM (Service Control Manager), 3 manual start, 4 disabled (note, 0 and 1 can only be used for driver)

3, ErrorControl error control: 0 Ignore, 1 continue and warning, 2 switch to LastKnownGood settings, 3 blue screen

4, servicebinary service program location

All right.. Run the command under CMD

rundll32.exe setupapi,installhinfsection DefaultInstall C:/sysnap/sysnap.inf

It is not easy to install a service called Sysnap. Of course later. INF file installation Service sometimes is not very good,,, the following we are compiled to achieve,,, is also the main purpose. Let's talk a little bit about theory.

3 Some basic theoretical knowledge about services

The WIN32 service consists of three parts: the service Application, the service control program SCP, and the service management manager SCM.

Service Application: That is the next program that we want to implement, he is an EXE file. Or it can be. DLL, here we are Sysnap.exe

Service Control Program: a function block that controls the service application and a bridge between the service application and the Service Manager (SCM)

Service Control Manager: responsible for loading and initializing the AUTO_ATRT service program, SCM maintains the Registry service database, located in: Hkey_local_machine/system/currentcontrolset/services. The sub-keys under it are the installed service and the driver service. The name of each subkey is the service name, which is specified by the CreateService function of the service security program when installed

And then don't write it. You can refer to <<inside windows 2000>> What they say is good enough ..., not enough inside to deal with a lot of things. Recommended to look at the following procedures ... It's better to refer to them if you don't understand them. Because this program doesn't require you to understand them all.

41 Service creation process a service creation process and basic composition

A write our main () function, which must call the StartServiceCtrlDispatcher function within 30 seconds: So our EXE file is registered in the SCM.

B Write Our ServiceMain (), ServiceMain () to call the RegisterServiceCtrlHandler Registration service control handler immediately, Then use the handle returned by RegisterServiceCtrlHandler to send state information to the SCM, then start to complete the actual service tasks and worker threads, and once the thread starts, ServiceMain () waits for an event to occur, knowing that the service is stopped, ServiceMain () only returns

C Write our control processor Servicectrlhandler, accept requests from the SCM and react, in fact the request is generally the following values (also can be defined by themselves)

Stop service: Service_control_stop

Suspension of service: Service_control_pause

Resume suspended service: Service_control_continue

Returns the update status information for the service: service_control_interrogate

D Write the function of the service to implement, that is, what we are going to do with the service, this is still the output computer user name

Visible, a complete service includes:

Main (): He tells SCM some information about ServiceMain ()

ServiceMain (): Start Servicethread () and tell SCM some information about the control processor

Servicectrlhandler: Accept and respond to requests from the SCM

Initthread (): Opened by ServiceMain () to perform our task, is to set up a thread to run our task

5 details of each basic function.

A Main ()

SCM is a process that manages all the services of the system, and when the SCM starts a service, it waits for the main thread of a process to call StartServiceCtrlDispatcher (), which translates the calling process's live threads into the control allocator, and the control allocator starts a new thread. New thread runs the ServiceMain () for each service in the allocation table

B ServiceMain ()

Is the entry point for the service. It runs in a separate thread, primarily for the service registration control processor, which instructs the control allocator to call Servicectrlhandler () to process the SCM request, and returns a handle when the registration is complete

By calling SetServiceStatus, use this handle and Service_status to report the service status to the SCM,,, because such actions often occur,,, so we write this process as a function reportstatustoscmgr ()

RegisterServiceCtrlHandler (Strservicename, (lphandler_function) servicectrlhandler);

The Reportstatustoscmgr () is then called to report the service status Reportstatustoscmgr () to the SCM;

Creates an event at the end of the function that will call the event to keep the function running until the SCM makes a stop request to return CreateEvent ();

Create a thread to run our service function sysnap ();

Finally Servicethread () returns ServiceMain (), ServiceMain () call WaitForSingleObject ()

C Servicectrlhandler ()

Check what the SCM has sent and responded to ... When the user shuts down the system, all the control processing to call SetServiceStatus settings Service_accept_shutdown control code to receive Service_control_shutdown control code, if the service takes time to clear, it can send stop_pending status messages, along with a wait time, so that the service controller knows how long to stay until the reporting system service shuts down, in any case, there is a service controller waiting time to prevent the service from staying in the shutdown state. To change this time limit, you can modify the WaitToKillServiceTimeout value in the Hkey_local_machine/system/currentcontrolset/control.

Switch (Ncontrolcode)

{

Case Service_control_shutdown:

Case SERVICE_CONTROL_STOP:

nservicecurrentstatus=service_stop_pending;

Success=reportstatustoscmgr (service_stop_pending,no_error,0,1,3000);

Killservice ();

Return

Default

Break

}

6 Some of the data structures and API descriptions used

Originally wanted to write,, forget it. Check msdn///oneself tired .... I'll inject some of the code below.

Here is the direct code bar ... You can compile it yourself

Sv.exe the Code

#include <stdio.h>

#include <windows.h>

#include <winsvc.h>

Define some global variables and functions

void ServiceMain (DWORD argc, LPTSTR *argv);

void Servicectrlhandler (DWORD dwcontrolcode);

SCM Reporting Service status information

BOOL Reportstatustoscmgr (DWORD dwcurrentstate, DWORD Dwwin32exitcode,

DWORD Dwservicespecificexitcode, DWORD Dwcheckpoint,

DWORD dwwaithint);

BOOL Initthread (); Create threads to run our tasks

DWORD sysnap (Lpdword param); The tasks we need to accomplish in this service

HANDLE Hservicethread;

void Killservice ();

Char *strservicename = "Sysnap"; Identify the internal name of the service

Service_status_handle Nservicestatushandle; Stores the handle returned by the call RegisterServiceCtrlHandler

HANDLE killserviceevent;

BOOL nservicerunning;

DWORD Nservicecurrentstatus;

void Main (int argc, char* argv[])

{

An array of service_table_entry struct types that contains the entry function and string name of each service provided by the calling process. The last element in the table must be NULL, indicating that the entry table ends

Service_table_entry servicetable[]=

{

{strservicename, (lpservice_main_function) ServiceMain},

{Null,null}

};

BOOL success;

The StartServiceCtrlDispatcher function is responsible for thread attached the program main line to the Service control management program.

Success=startservicectrldispatcher (servicetable);

if (!success)

{

printf ("fialed!");

}

}

void ServiceMain (DWORD argc, LPTSTR *argv)

{

BOOL success;

Register the Servicectrlhandler as a service controller, accept requests from the SCM and make processing,

Nservicestatushandle=registerservicectrlhandler (Strservicename,

(lphandler_function) Servicectrlhandler);

Determine if registration is successful, otherwise return

if (!nservicestatushandle)

{

Return

}

Report Service status information to SCM after successful registration, because the service is not initialized, so the current service status is Service_start_pending

Success=reportstatustoscmgr (service_start_pending,no_error,0,1,3000);

if (!success)

{

Return

}

Creates an event that will be used at the end of the function to keep the function running until the SCM makes a stop request to return

Killserviceevent=createevent (0,true,false,0);

if (killserviceevent==null)

{

Return

}

Reporting Service status information to the SCM

Success=reportstatustoscmgr (service_start_pending,no_error,0,2,1000);

if (!success)

{

Return

}

Initthread () Create a thread to run our Sysnap () function

Success=initthread ();

if (!success)

{

Return

}

Our service starts to run the task, the current state is set to Service_running

nservicecurrentstatus=service_running;

Success=reportstatustoscmgr (service_running,no_error,0,0,0);

if (!success)

{

Return

}

The Sysnap () function returns ServiceMain () after it runs out, ServiceMain () calls WaitForSingleObject because the service is stopped before ServiceMain () does not end

WaitForSingleObject (Killserviceevent,infinite);

CloseHandle (killserviceevent);

}

Report the service status information to the SCM, which can be said to be an update, and it accepts parameters that are service_status struct members

BOOL Reportstatustoscmgr (DWORD dwcurrentstate, DWORD Dwwin32exitcode,

DWORD Dwservicespecificexitcode, DWORD Dwcheckpoint,

DWORD dwwaithint)

{

BOOL success;

Service_status Nservicestatus; Defines a service_status type structure nservicestatus

nservicestatus.dwservicetype=service_win32_own_process; Indicates that our service is a service exclusive to a process

Nservicestatus.dwcurrentstate=dwcurrentstate; Current service status

//

if (dwcurrentstate==service_start_pending)

{

Nservicestatus.dwcontrolsaccepted=0; Initialization of the service is not complete

}

Else

{

Nservicestatus.dwcontrolsaccepted=service_accept_stop//Notifies the SCM service which domain to accept. STOP and shutdown requests are allowed here

| Service_accept_shutdown;

}

Dwservicespecificexitcode is useful when you terminate the service and report the exit details. The service is initialized without exiting, so the value is 0

if (dwservicespecificexitcode==0)

{

Nservicestatus.dwwin32exitcode=dwwin32exitcode;

}

Else

{

Nservicestatus.dwwin32exitcode=error_service_specific_error;

}

Nservicestatus.dwservicespecificexitcode=dwservicespecificexitcode;

//

Nservicestatus.dwcheckpoint=dwcheckpoint;

Nservicestatus.dwwaithint=dwwaithint;

After setting the Nservicestatus, report the service status to the SCM.

Success=setservicestatus (Nservicestatushandle,&nservicestatus);

if (!success)

{

Killservice ();

return success;

}

Else

return success;

}

BOOL Initthread ()

{

DWORD ID;

Hservicethread=createthread (0,0,

(Lpthread_start_routine) Sysnap,

0,0,&ID);

if (hservicethread==0)

{

return false;

}

Else

{

Nservicerunning=true;

return true;

}

}

DWORD sysnap (Lpdword param)

{

while (nservicerunning)

{

Beep (450,150);

Sleep (4000);

}

return 0;

}

void Killservice ()

{

Nservicerunning=false;

SetEvent (killserviceevent);

Reportstatustoscmgr (service_stopped,no_error,0,0,0);

}

void Servicectrlhandler (DWORD dwcontrolcode)

{

BOOL success;

Switch (Dwcontrolcode)

{

Case Service_control_shutdown:

Case SERVICE_CONTROL_STOP:

nservicecurrentstatus=service_stop_pending;

Success=reportstatustoscmgr (service_stop_pending,no_error,0,1,3000);//update the service status to Servicde_stop_pending before stopping the service

Killservice ();

Return

Default

Break

}

Reportstatustoscmgr (nservicecurrentstatus,no_error,0,0,0);

}

Svload.exe the Code

#include <stdio.h>

#include <windows.h>

#include <winsvc.h>

int main (int argc, char* argv[])

{

char* showinfo= "Sysnap ' s first Windows service"; Note the conversion of wide characters (L)

char* showname= "Sysnap";

char* sv_path= "C://sysnap//sv.exe";

Sc_handle Hsysnap;

Sc_handle Hscmanager;

Hscmanager=openscmanager (0,0,sc_manager_create_service);

if (!hscmanager)

{

printf ("Failed");

return 1;

}

Hsysnap=createservice (Hscmanager,text (ShowName),

TEXT (Showinfo),

Service_all_access,service_win32_own_process,service_demand_start,

Service_error_normal,

Sv_path,

0,0,0,0,0);

if (! HSYSNAP)

{

Closeservicehandle (Hscmanager);

printf ("Failed");

return 1;

}

Closeservicehandle (HSYSNAP);

Closeservicehandle (Hscmanager);

return 0;

}

The two EXE files altogether 334K .... If you don't want to compile, I can send them to your mail argentea.

Ha ha.. Thank you for a boutique. When I wrote it, I thought it was clear. But now I'll watch it again. is relatively long. I've got his whole body up,,, look, it's not messy.



void Main ()
{
Call StartServiceCtrlDispatcher (), give control to the control dispenser, control the dispenser to create a new thread to run the ServiceMain. Which is to actually enter the service
}

void ServiceMain (DWORD argc, LPTSTR *argv)
{

RegisterServiceCtrlHandler Register as a service controller, accept requests from SCM and make processing


Creates an event that will be used at the end of the function to keep the function running until the SCM makes a stop request to return

Create a thread to run our functions


Returns ServiceMain () after the function has run, ServiceMain () call
}



BOOL Reportstatustoscmgr ()
{
Populate Service_status Members: and pass it as a parameter to Etservicestatus () Reporting service status to SCM

}

BOOL Initthread ()
{
Create a thread that runs Sysnap ()
}

DWORD sysnap (Lpdword param)
{
The work we're going to do
}

void Killservice ()
{
Stop Service
}

void Servicectrlhandler (DWORD dwcontrolcode)
{
Accept and respond to requests from the SCM. Here you have to implement several functions yourself;
}

In short remember to look at the time with main (), ServiceMain () and Servicectrlhandler () as the center. Other functions are relatively simple.

http://blog.csdn.net/jiangxinyu/article/details/5265673

The principle and implementation of Windows service programs (services are divided into WIN32 services and system services)

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.