Windows Services Learning (reprint)

Source: Internet
Author: User
Tags session id

Reprint: http://blog.csdn.net/fakine/article/details/42107571

First, learning a bit

1, the Machine service view: services.msc/s
2, the Service manual installation (using Sc.exe):

Create a service
SC create ServiceName binpath= "C:\MyServices\Test.exe"

"=" has a space after

Delete Service

SC Delete ServiceName

Start the service

net start ServiceName

Stop Service

net stop ServiceName

3, the service is in the process of killing, service also stopped.
4. Service Delete, error message:
D:\>SC Delete Sample_srv
[SC] DeleteService FAILED 1072
D:\>SC Stop Sample_srv
[SC] ControlService FAILED 1052
WORKAROUND: The service cannot have a UI box such as the MessageBox, the dialog box will not pop out, but the program will be blocked, resulting in the inability to stop, unable to delete the service, need to shut down the restart, services can be cleared. In addition, if the service starts a process that does not have an interface, the functionality of the new process can still be performed.
5, how to use DebugView debugging
Capture Global Win32 needs to be selected in capture
6, the interface of the service. Interactive Services
The most convenient way is to use the Wtssendmessage API to pop up a dialog box without any additional work.
If it is a direct MessageBox API, or if the winexec directly launches a GUI process, the service type parameter needs to be taken with the service_win32_own_process on CreateService | The service_interactive_process parameter. However, any UI under Win7 causes the Interactive Service Detection dialog box to be displayed. The section of the network "open user winsta0" without using the CreateProcessAsUser API code in the same way as the "Interactive Service Monitoring" dialog box, is not reliable, is estimated to be a masterpiece under XP. The problem with this pop-up window is solved, MSDN gives the solution--using the CreateProcessAsUser API to launch a new process interface, the service process and the interface process can use named pipes for interprocess communication.
If you do not set the parameters mentioned above, then the service in the start subprocess or the whole process of the sun process, can not appear any interface, otherwise the service is dead, and can not stop, unable to delete the service, need to shut down the restart, the service can be cleared.
7. If the CreateProcessAsUser API uses the parameter create_new_console, then from the Process Explorer you will not see the relationship between the service process and the initiated processes.
8. Display the dialog box through the Wtssendmessage API.
DWORD resp = 0;
Wtssendmessage (
Wts_current_server_handle,
Wtsgetactiveconsolesessionid (),
"Hello", 5,
"Hello_2", 7,
0, 0, &RESP, false);
9, a perfect example, including service procedures and interface procedures, as well as the communication between them. But some code can not compile, look at the idea of good.
Interaction between services and applications at user level in Windows Vista
Http://www.codeproject.com/Articles/36581/Interaction-between-services-and-applications
10, very perfect start GUI process from the service.
NT Services 2013

http://www.codeproject.com/Articles/640245/NT-Services-2013
10, the service boot start:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms681957 (v=vs.85). aspx
11. Sessions,desktops and Windows stations
Http://blogs.technet.com/b/askperf/archive/2007/07/24/sessions-desktops-and-windows-stations.aspx
12, a fairly simple service program: http://www.vckbase.com/index.php/wv/1193
13, a complete example of the installation service program, the Service Program: http://blog.csdn.net/itcastcpp/article/details/7079574 (the code appears to be from Windows core programming, Or From here: http://bbs.pediy.com/showthread.php?t=114122)
14, a monitoring sub-process services, if the child process has an interface, it will show the Win7 under the pop-up window, this example is not very good, the code logic simple look on the line.
Http://www.codeproject.com/Articles/16488/A-Windows-Service-Application

Second, MSDN Reading

http://msdn.microsoft.com/en-us/library/ms685477 (v=vs.85). aspx
Service entry point
The service program is generally written as a console application, and the main function is the entry function, and the parameters of the main function are specified in the CreateService function. When the SCM starts a service program, the SCM waits for the service program to call the StartServiceCtrlDispatcher function, and if the service process does not call the function in time, it causes the service to fail (for example, the StartService function fails when manually started). For the timing of the StartServiceCtrlDispatcher function call, there are the following rules:
1, if the service program is the service_win32_own_process type, the service program must call StartServiceCtrlDispatcher immediately in the main thread, the initialization work can be done after the service starts, that is, in the service main function.
2, if the service is a service_win32_share_process type, and the initialization is owned by all the services in this program, it can be executed before calling StartServiceCtrlDispatcher, but can only execute for 30 seconds at most. Consider starting a new thread to do the public initialization task. If there are service-independent initialization tasks, you still need to do it in the service main function after the service starts.
The parameter of the StartServiceCtrlDispatcher function is an array of service_table_entry structures containing: 1, the name of the service, which is only used in the service main function, if the service is Service_win32_own_ Process type, then the name can be ignored; 2, the service main function pointer.
If the StartServiceCtrlDispatcher function succeeds, the calling thread (the main thread of the service process) does not return until all services enter the service_stopped state. The calling thread plays the role of controlling distribution, doing something like this: 1. Start a new thread at the start of a new service to invoke the service main function (idea: The service's task is done in a new thread), 2, when the service has a request (note: The request is sent to it by SCM), Call its corresponding handler (idea: This is equivalent to the main thread "caught", which is waiting for the control message and processing the message).
Demo Code: http://msdn.microsoft.com/en-us/library/windows/desktop/ms687416 (v=vs.85). aspx

http://msdn.microsoft.com/en-us/library/ms685984 (v=vs.85). aspx
Service main function
When the service control program starts a new service, the Service controls Manager (SCM) starts the service process, and then the service process sends the start request to the control allocator, which controls the allocator to create a new thread to execute the service main function. The service main function needs to do something like this:
1. Initialize all global variables
2, call the RegisterServiceCtrlHandler API to register the service's control request handler function, the return value of the function is the service state handle, when notifying the SCM current service state.
3. Completion of initialization. If the initialization time is short (less than 1 seconds), initialization can be performed directly in the service main function. Otherwise, you should choose one of the following ways to do it:
(1) Call the SetServiceStatus API to set the service state to Service_running, while the dwcontrolsaccepted in the Service_status struct is set to 0, Ensure that the SCM does not send control requests to the service during initialization, and that SCM can manage other services. This approach is recommended in order to improve performance, especially for Autorun services.
(2) Call the SetServiceStatus API to set the service state to service_start_pending, which will not receive the control request and define a time-out. If the initialization time of the service exceeds the predefined wait time, the timeout must be redefined periodically by calling the SetServiceStatus API, but to ensure that the initialization is actually progressing, because at this point the SCM thinks the initialization is progressing and it blocks the opening of other services. If a time-out occurs and the pending progress information remains unchanged, the SCM or Service control program (which can be written to start the service) considers that an error has occurred and needs to terminate the service (but if the service shares the process with other services, it will not end the process where the service is located). Using this method of initialization, you can increase the value of "Checkpoint" by calling the SetServiceStatus API periodically based on the actual progress, and the initiator of the service can either QueryServiceStatus or Queryservicestatusex API to get the value of the checkpoint, it also gets the service initialization progress.
4, when the initialization is complete, call the SetServiceStatus API into the service_running state, you can receive the control request.
5, perform the service task. If no task is currently in operation (that is, the service main function is finished), control is given back to the caller (that is control dispatcher). If a single service calls StartServiceCtrlDispatcher, the service main function is finished, StartServiceCtrlDispatcher will not return until the service enters the Stop service_stopped state. The process does not end. In general, we will not give up control, you can write a dead loop to work, anyway, the main thread exit will be the main function of the service to end the thread. In addition, any change in service status is done through SetServiceStatus.
6, if an error occurs during the service initialization and execution of the task, the service enters the service_stopped state in the last thread to be ended, and if the cleanup of the end service takes a long time, it needs to go into the service_stop_pendding state and perform cleanup work. External error messages can be communicated through the Dwservicespecificexitcode and Dwwin32exitcode parameters of the service_status structure.
Demo Code: http://msdn.microsoft.com/en-us/library/windows/desktop/ms687414 (v=vs.85). aspx

http://msdn.microsoft.com/en-us/library/ms685149 (v=vs.85). aspx
Service Control handler function
Each service has a control handler that is called by the control dispatcher when the service process receives a control request, so the function is executed in the control dispatcher thread, which is the main thread of the service process. When the service control handler is called, the service can be set to a different state through the SetServiceStatus API (that is, what state is notified of the SCM current service).
The outside world can send control requests via the ControlService API. All services must receive and process Service_control_interrogate control codes, which control codes can be received via the SetServiceStatus API, if you want to receive Service_control_ Deviceevent control Code, the RegisterDeviceNotification API must be called, and the service can receive user-defined control codes.
The control handler function must return within 30 seconds (but in fact I have tested SLEEP40 second return does not cause SCM to stop), and when there is a long time task, a new thread must be started to execute. For example, when you stop, you should allow the service to enter the Service_stop_pendding state, open a new thread to perform the task, and let the service control handler return immediately.
When the system shuts down, if Service_accept_preshutdown is set, the control handler function can receive the Service_control_preshutdown control code. The SCM waits for all services to stop, or the wait time exceeds the shutdown notification timeout value, which can be set through the ChangeServiceConfig2 API. Use caution when using this control code to avoid blocking the shutdown.
After the notification is completed before the shutdown, all services set up with Service_accept_shutdown can receive the Service_control_shutdown control code in the order in which they are installed. Typically, a service has 20 seconds to process a task before it shuts down, and the system shuts down after timeout, regardless of whether the service is completing the task. The service is still running when the system is in a shutdown state.
If a service takes more time to clean up, it sends the stop_pending state and sets the wait time. However, to prevent the service from shutting down, there is a limit to timeouts.
During shutdown, when the SCM sends a shutdown message, the dependencies between services are not considered, and all of the services may fail because the service it relies on has stopped. You can set the service shutdown dependency manually or through the API.
Demo Code: http://msdn.microsoft.com/en-us/library/windows/desktop/ms687413 (v=vs.85). aspx


http://msdn.microsoft.com/en-us/library/ee126211 (v=vs.85). aspx
Service state transitions
The service is responsible for reporting status changes to the SCM. Service control procedures and systems can only be obtained from SCM to the state of the service. The service program sets the service state through the SetServiceStatus API.
The initial state of the service is service_stopped, when the SCM starts the service, the service state enters the service_start_pending state, invokes the service main function, then the service completes the initialization, sets the acceptable control request, Then through the SetServiceStatus notify SCM to enter the Service_running state, if entered is not service_running state, the SCM, service monitoring tool will think that the service failed to start.
The SCM only sends the specified control request to the service (except for the service_control_interrogate request, it does not need to be specified). The dwcontrolsaccepted member of the Service_status struct specifies which control requests are required for the demand notification service. If you want to receive device events, you need to set through the RegisterDeviceNotification API.
Typically, a response to a control request changes the service state. Control requests that can cause changes in service status include: Service_control_stop, Service_control_pause, Service_control_continue. If the service response time is long, you must create a second thread to complete the task and tell the SCM to enter the appropriate pendding state, complete the task, and then go to the completion state. For better performance, Vista and later versions of the system recommend using the thread pool.
Service status valid conversion diagram:


The state of the service escalated to the SCM determines the interaction with the SCM (that is, the control request that the SCM can then send to the service). For example, if the service tells the SCM that it has entered the service_stop_pendding state, which means the service is shutting down, the service can only notify the SCM to enter the service_stopped state.
Control Service Stop demo:http://msdn.microsoft.com/en-us/library/windows/desktop/ms686335 (v=vs.85). aspx

http://msdn.microsoft.com/en-us/library/ms685145 (v=vs.85). aspx
Services and Registration forms
The service cannot access Heky_current_user and HKEY_CLASSES_ROOT, and the RegOpenCurrentUser and Regopenuserclassesroot functions should be used.
Jane Knot:
The process of the entire service can be understood like this: assuming that the process has only a single service, the SCM pulls the service process up, and the main thread of the service process invokes the Service control distribution function, which is not returned until the service is stopped or the service fails to open. The Service control distribution function starts a new thread to execute the service main function, and the service main function registers the control handler function, which is a callback function, which is called by the main thread to respond to external notifications, and the control callback function sets the service into a different state according to the notification, which also tells the SCM service to enter another state. When the state of the service enters the service_stopped state, the service control distribution function returns, the main thread ends, and the process ends.

http://msdn.microsoft.com/en-us/library/windows/desktop/ms683502 (v=vs.85). aspx
Interactive services
In general, a service is a console program that does not require interaction without an interface. However, some services sometimes require interaction with the user.

Services in the Vista system cannot interact directly with the user.

The user interacts indirectly with the service.
On all versions supported by Windows, you can use the following technology:
1. Use the Wtssendmessage function to display the dialog box to the user.
2. Create a hidden GUI application that uses the CreateProcessAsUser API to enable the application to run in an environment that can interact with the user. The GUI program uses IPC to communicate with the service program, and if the communication uses a named pipe, the service can differentiate a multiuser process by providing a pipe name based on the session ID.
Use interactive services.
By default, the service uses a non-interactive "window station" and cannot interact with the user. However, an interactive service can display the user interface and receive user input.
......
The window displayed in this way is a popup prompt. It doesn't work.
The final document also says: All services run in Terminal Services session 0. Therefore, if an interactive service displays the user interface, only those who enter session 0 will be able to see, all under Win7 a prompt box to let the user into another interface, that is, session 0.

Iii. Summary

Note that starting the GUI process from the service can solve the problem of UAC bullet box when the program requires administrator privileges under Win7. While the service starts the GUI process, the main need is to use the CreateProcessAsUser API. Cannot let the service process pop up a beautiful window, can only pop a messagebox directly, if you want to use the service's high privilege to do something, and want to have a nice user interface, you can let the UI process to work with the service process, the UI process is responsible for interacting with the user, which requires involving interprocess communication (IPC), Using Named pipes also makes it easy to implement a demo, which is not said here.
Service Demo Code: Https://github.com/cswuyg/simple_win/tree/master/my_service_example, includes: The service process, the service to start the GUI process, the service control process code.

2014.3 Supplement

1, Service programming: http://msdn.microsoft.com/en-us/library/windows/desktop/ms685969 (v=vs.85). aspx
2, a complete service demo:http://msdn.microsoft.com/en-us/library/bb540476 (v=vs.85). aspx
3, the Service control callback function response:
It is necessary to correctly and promptly notify SCM of the change in the state of the service in the control handle function.
After the user has set the service to a certain state through the service panel, the system determines whether the operation is valid by checking the status of the service in the SCM, so, for the service, it is only required to modify the corresponding state in the control handle according to the notification code. Whether the service is really stopped, depends on the will of our program.
If the user operates a "stop" service, but our program does not notify the SCM that the service status changes, it will cause "Windows cannot stop ...." Service "window, this happens two times after the service process exits.
4, how to modify some of the properties of the service, including enabled, Disabled, boot run service (this can also be set at createservice time Service_Auto_Start), description information:/HTTP msdn.microsoft.com/en-us/windows/desktop/ms682006 (v=vs.100). aspx
5, in writing the start-up operation service, need to have their own log, to locate which block is not executed, Windows itself has logs, but too little information, Windows logs: command line run Compmgmt.msc, navigate to System Tools \ Event Viewer \ Windows logs \ System, you can see the information about service startup. When I wrote it, there was an error that the service could not boot: "Wait for the connection timeout for the Cswuyg_svc service (30000 milliseconds)". After many tests, found that the service process EXE from the debug version of the release version of the solution, it is estimated that the debug mode performance is too poor, causing the service main function thread can not be started in a timely manner (from the log to see the service main function is not executed to).

Windows Services Learning (reprint)

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.