RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Five Steps to Writing Windows Services in C : Page 5

Windows services are convenient for running background apps and for performing tasks that don't require user interaction. And C (not C++) is the best choice for learning the basics of these console applications. Build and implement a simple service to query the amount of available physical memory and write the result to a text file. Then use what you've learned to write your own Windows services.

Step 5: Testing Your Service
Start the MemoryStatus service from the Services applet. If there are no initialization errors, the execution should start successfully. Wait for a while, then stop the service. Examine the service's output in the memstatus.txt file under the C:\MyServices folder. On my computer, I obtained the following:

Monitoring started.
Monitoring stopped.
To test the behavior of the MemoryStatus service in case of errors, you can make the memstatus.txt file read-only. In this setting, the service will not start.

Remove the read-only attribute, start the service, and reapply read-only. The service should stop its execution because writing to the log fails. If you refresh the contents of the Services applet, you will see that service status is stopped.

On to Bigger and Better Servcies
Understanding the basic concepts of Win32 services, allows you to better use C++ for designing a wrapper class. A wrapper class hides the calls to the low-level Win32 functions and provides a comfortable generic interface. Alter the MemoryStatus program code to create your own services that fit your needs! To perform more complicated tasks than one demonstrated in this article, you can create multithreaded services to divide the job between several worker threads and monitor their execution from the ServiceMain function.

Yevgeny Menaker is a developer, author, and Linux consultant with more than 5 years of experience. For the past three years, Yevgeny has been focused on developing new and advanced Internet technologies and Internet/COM/ATL applications. He is currently working on migrating to .NET technology. He is the lead author of "Programming Perl in the .NET Environment" (Prentice-Hall). Additionally, he worked with Object Innovations as a Linux consultant. He can be reached at jeka_books@hotmail.com.
Email AuthorEmail Author
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date