Windows Background Services Program authoring

Source: Internet
Author: User

Windows Background Services Program Authoring

1. Why to write a background service program

There is a program in the work to be written in the form of back-office services, groping a bit, share with you.

In the Windows operating system, a background process is called a service. A service is an application type that runs in the background and usually does not have an interactive interface. Service applications can often provide users with functionality, both locally and over the network, for other processes. By registering a program as a service, you can make your program run first as the system starts, and finally stop with the system shutting down. You can also manually control the startup and shutdown of the service by Windows Service Manager.

2. Writing a background service program step

Windows provides a set of background service program programming interfaces that users need to follow when writing a background service program, or the service program does not work properly.

A service program is typically written as a console-type application, and a program that adheres to the requirements of the Service Control Manager interface, in general, contains the following three functions:

1) The main function of the service program (main): Call the system function startservicectrldispatcher The main thread of the connector to the Service Control Manager.  

As with other processes, themain function is the entry function for the service process, and the Service Control Manager (SCM) starts the service program from the main The function starts execution. In the entry point function to complete The initialization of the ServiceMain, the exact point is to initialize an array of service_table_entry Structures, This structure records the name of all services contained within the service and the entry point function of the service. The interface StartServiceCtrlDispatcher is then called .

the function framework for the Main function is as follows:

int _tmain (int argc, _tchar* argv[])

{

Service entry point function table

Service_table_entry dispatchtable[]=

{

{TEXT (Szservicename), (lpservice_main_function) Service_main},

{Null,null}

};

if ((argc>1) && ((*argv[1]=='-') | | (argv[1]=="/")))

{

/*

The number of parameters greater than 1 is the installation or removal of the service, which is performed by the user

Of course, you can also say this part of the function to write another program to achieve

*/

if (_STRICMP ("Install", argv[1]+1) ==0)

{

Installservice ();

}

Else if (_STRICMP ("Remove", argv[1]+1) ==0)

{

RemoveService ();

}

Else if (_STRICMP ("Debug", argv[1]+1) ==0)

{

Bdebugserver=true;

Debugservice (ARGC,ARGV);

}

}

Else

{

/ *

If you fail to match the above parameter, the Service Control Manager may be the one that started the program. Call the startservicectrldispatcher function now

*/

G_logout. Logout ("%s\n", "Enter StartServiceCtrlDispatcher ...");

notifies Service Manager to create a service thread for each service

if (! StartServiceCtrlDispatcher (dispatchtable))

G_logout. Logout ("%s\n", "StartServiceCtrlDispatcher failed.");

Else

G_logout. Logout ("%s\n", "StartServiceCtrlDispatcher OK.");

}

return 0;

}

After the SCM starts a service program, it waits for the program's main thread to tune startservicectrldispatcher. If that function is not called within two minutes,SCM will consider the service to be problematic and call terminateprocess to kill the process. This requires your main thread to call StartServiceCtrlDispatcher as quickly as possible .

2) Service entry point function (servicemain): Perform service initialization tasks, while service processes that perform multiple services have multiple service entry functions.  

In the service entry function, the service control callback function must be registered immediately. The function setservicestatus is then called to notify the SCM Service of the current state, or the SCM will assume that the service failed to start.

The ServiceMain function framework is as follows:

void WINAPI Service_main (DWORD dwargc, LPTSTR *lpszargv)

{

Registration Service Control handler function

Sshstatushandle=registerservicectrlhandler (TEXT (szservicename), Service_ctrl);

If registration fails

if (!sshstatushandle)

{

G_logout. Logout ("%s\n", "RegisterServiceCtrlHandler failed ...");

Return

}

initializing members in a service_status structure

ssstatus.dwservicetype=service_win32_own_process; there is only one separate service in the executable file

ssstatus.dwservicespecificexitcode=0;

ssstatus.dwcontrolsaccepted = Service_accept_stop; allow SCP to stop the service

Update Service Status

if (Reportstatustoscmgr (service_start_pending,// service status, service is still initializing

No_error,

)// Wait Time

Svcinit (DWARGC, LPSZARGV); Service initialization function

Else

G_logout. Logout ("%s\n", "Reportstatustoscmgr service_start_pending failed ...");

}

Service initialization function svcinit:

The function is more important. Create a wait event in the function, and then wait for the event. The thread is in a pending state until the service is received by the request until the message is stopped.

VOID Svcinit (DWORD dwargc, LPTSTR *lpszargv)

{

/* Create Event * /

Ghsvcstopevent = CreateEvent (

NULL,//default security attributes

TRUE,//manual reset Event

FALSE,//not signaled

NULL); No Name

if (ghsvcstopevent = = NULL)

{

Reportsvcstatus (service_stopped, no_error, 0);

Return

}

Report running status when initialization are complete.

Reportsvcstatus (service_running, no_error, 0);

the creation of the service thread is performed here ...

while (1)

{

wait for the stop event to be triggered

WaitForSingleObject (Ghsvcstopevent, INFINITE);

Reportsvcstatus (service_stopped, no_error, 0);

Return

}

}

3) Control Service handler function (Handler): Referenced by the control distribution thread when the service program receives a control request. (Here is Service_ctrl).  

void WINAPI Service_ctrl (DWORD dwctrlcode)

{

processing control Request Code

Switch (Dwctrlcode)

{

Update the service status to servicde_stop_pending before stopping the service.

Case SERVICE_CONTROL_STOP:

Reportstatustoscmgr (service_stop_pending,no_error,500);

Servicestop (); implemented by a specific service program

/*ssstatus.dwcurrentstate=service_stopped;*/

other control requests ...

Default

Break

}

}

3. Precautions

1) Install the service can write another program, also can and in the service program, relatively simple, here is not introduced.

2) It is important to create a wait event in the service initialization function Svcinit , which triggers the event after the service has received a service stop message.

3) Service_main returns immediately after the event is triggered and the service process exits.

Windows Background Services Program authoring

Related Article

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.