Using C + + for Windows development: Windows Service Enhancements

Source: Internet
Author: User
Tags bool continue thread

Directory

Delay Automatic start service

Improved shutdown predictability

Failed operation and controlled stop

Reduce permissions

Protect service data

Protect other items with a restricted brand

Receive service Notifications

Subsequent content

The status of windows® service development has not changed significantly since the presence of services in Windows NT®, but Windows vista® and Windows server®2008 have broken the deadlock. Many of these features are intended primarily to generate more secure services in a simpler way, but some features are designed to improve the overall responsiveness and reliability of Windows in service functions that are not related to security.

Delay Automatic start service

Services can be configured to start only when a specific request is received through the StartService function. This service is called on-demand start service. Alternatively, they can be configured to start automatically during the startup process of the operating system. These are known as automatic startup services that make sense for services that are necessary for many functions that are available at all times, or other services. However, some autostart services do not absolutely need to run when users log on to the computer, because they may not be used immediately.

Windows Vista takes another step to reduce the startup time of Windows by providing a tool for the Autostart service to start only after Windows completes its own startup process. Specifically, activation of the delayed Autostart service is performed two minutes after the normal autostart service completes. The Service Control Manager (SCM) can also create a lower priority primary service thread to ensure that any logged-on user is unaffected by the delayed Autostart service. The priority is reset to "normal" after the service updates its running state. If you find that a deferred autostart service does not start when your application needs it, you can force it to start quickly by using the StartService function.

The following function shows how to control this option, which should be invoked by the installation program of the service:

bool ChangeDelayedAutoStart(
  SC_HANDLE service, bool delayed)
{
  ASSERT(0 != service);
  SERVICE_DELAYED_AUTO_START_INFO info = { delayed };
  return 0 != ::ChangeServiceConfig2(
    service,
    SERVICE_CONFIG_DELAYED_AUTO_START_INFO,
    &info);
}

The service handle determines the service to be configured. This handle can be obtained by calling the OpenService or CreateService function. The CHANGESERVICECONFIG2 function allows you to change many more advanced service configuration options. In this case, I used the service_config_delayed_auto_start_info tag to tell the function to use the Service_delayed_auto_start_info pointer as its third argument. If it fails, CHANGESERVICECONFIG2 returns a value of 0, which can get detailed error information by calling the GetLastError function.

Improved shutdown predictability

A previous version of Windows Vista, it is not always possible to ensure that the service stops normally when the computer shuts down. When the system notifies the SCM to shut down, it only takes about 20 seconds to indicate that all running services are stopped. If the time is too long, the system will end up roughly halting the SCM process. Because a service that does not shut down normally needs to handle an inconsistent state when it restarts again, this can cause many problems, including increasing startup time.

Windows Vista introduces new pre shutdown notifications that the service can request to receive. If you are developing a service that must be shut down gracefully without requiring a quick shutdown, you can request a pre-shutdown notification from the SCM. SCM will wait (and possibly indefinitely) to stop all pre-shutdown services before executing the shutdown process of its traditional service. Although it is good for the service, it does not work for users who want the computer to shut down quickly. Therefore, you should limit this functionality to very critical services, preferably for one server scenario only.

The service indicates that it wishes to receive a pre-shutdown notification by including the Service_accept_preshutdown tag in its service state. The handler function for the service is then notified via the Service_control_preshutdown control code. Although Windows is willing to wait indefinitely for the pre-shutdown service to stop, the service must still respond to queries from the SCM and update the status of the service by increasing the checkpoint value. If the SCM determines that the service is not responding, it will eventually abort and the system will continue to shut down. Note that if the service handles Service_control_preshutdown control code, it will not receive the traditional Service_control_shutdown control code. In most cases, it is best to use a single shutdown program for all control code associated with a stop.

One of the most notable behavioral characteristics of SCM is that it communicates with only one service at a time. It has a specific meaning, such as the obvious meaning: if two applications (or threads) invoke service control functions (such as StartService or ControlService), SCM queues them and serves only one request at a time. Another situation where there are more problems is when Windows shuts down. The named pipe that is established between the SCM and the service is communicated by the SCM when the StartServiceCtrlDispatcher function is invoked. When SCM sends control code to a service, it communicates through a named pipe to the StartServiceCtrlDispatcher function in the service. It forwards the request to a handler for the special service (the shared Process service) and causes the handler to process it before returning the request. The problem is that you cannot block the processing function from blocking for a long time. If the service cannot respond within 30 seconds or if it responds, but there is no other service to control, the request sent by the SCM will eventually timeout.

As a service developer, you need to keep this in mind and never block the service handler functions. A well performing service should be able to accept requests, set tags or start some worker threads to process requests and return immediately. This allows the SCM to continue to communicate with other services when your service has time to process the request. Figure 1 shows how to perform a stop and close control code.

Figure1 processing stop and shutdown

DWORD WINAPI Stopthread (pvoid)
{
//perform any length shutdown operation
M_status.dwcurrentstate = service_stopped;  
VERIFY (:: SetServiceStatus (M_handle,
&m_status);
return 0;
}
...
Switch (Control)
{
Case service_control_stop:
Case service_control_shutdown:
Case Service_control_   Preshutdown:
{
m_status.dwcurrentstate = service_stop_pending;
  VERIFY (:: SetServiceStatus (M_handle,
&m_status));
CHandle thread (:: CreateThread (0,//default security
0,//default stack size
St Opthread,
This,//context
0,//No flags
0);//Ignore th  Read ID
break;
}
...
}

Control handlers that handle Service_control_stop, Service_control_shutdown, and Service_control_preshutdown control code set the state of the service to Service_stop_ PENDING, create a worker thread to work, and then return without further action. The Stopthread function can block functions when needed, and then set the state of the service to service_stopped, notifying the SCM that it can then let StartServiceCtrlDispatcher function to return and abort the process (assuming it is the last service of the shared Process service). Just keep in mind that if the service is in a pending state, the status of the service needs to be updated periodically with incremental checkpoint values to ensure that the SCM does not hang.

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.