Introduction to Windows Service(Process Killer)

Vuyiswamb
Posted by in .NET Framework category on for Advance level | Views : 24487 red flag
Rating: 5 out of 5  
 1 vote(s)

This Article will introduce you to the Windows Service. Our Example is a Service that kills unwanted Processes.


 Download source code for Introduction to Windows Service(Process Killer)

Introduction

Have you ever had a Process in your Server that takes up all the Memory? , did you wonder how you going to kill that process when it occurs? In this Article we are going to use Windows Service to kill the Process in every defined time intervals. Please note that you have to identity the culprit Service or Process. First of all you have to know what Windows Services are.

What is a Windows Service

Wikipedia says that Windows Service is a long-running executable that performs specific functions and which is designed not to require user intervention. Windows services can be configured to start when the operating system is booted and run in the background as long as Windows is running, or they can be started manually when required. They are similar in concept to a Unix daemon. Many appear in the processes list in the Windows Task Manager, most often with a username of SYSTEM, LOCAL SERVICE or NETWORK SERVICE, though not all processes with the SYSTEM username are services. The remaining services run through svchost.exe as DLLs loaded into memory.

Code

Well you only need you Visual Studio, well am using VS2005. Now when we create Windows Service, we dont create them like other Applications, we dont need a Form, because this is a Service, it does not need any interaction while it’s running. So Go to your Visual Studio and go to FILE--> NEW-->VISUAL C# and Collapse the tree and Choose "Windows”, and Choose Windows Service. Give it a Proper name like mine is Process_Killer, and Choose the Proper location where your Project will be saved. I have created a Folder for it, you can do that as well. This will be easier when you do the installation.

 

 The First Step is to add an App.config file, we are going to use it to Store the Time and the Process to Kill. after you have done that go to Solution Explorer and rename the Component from Service1 to "Process_killer", when done double Click on the Brownish area to view the Code , you will see that VS has already structured some code for you. Make sure that your Code looks like this

Config File

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

<appSettings>

<add key ="Process" value ="NotePad"/>

<add key ="Time" value ="50000"/>

</appSettings>

</configuration>

 

//and this

 

 

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Diagnostics;

using System.ServiceProcess;

using System.Text;

using System.Configuration;

using System.Threading;

namespace Process_Killer

{

public partial class Process_Killer : ServiceBase

{

String Process_Kill = ConfigurationSettings.AppSettings.Get("Process");

int Time = Convert.ToInt32(ConfigurationSettings.AppSettings.Get("Time"));

public Process_Killer()

{

InitializeComponent();

}

protected override void OnStart(string[] args)

{

 

 

Thread thread = new Thread(new ParameterizedThreadStart(DoWork));

thread.Start(Process_Kill);

}

 

protected override void OnStop()

{

// TODO: Add code here to perform any tear-down necessary to stop your service.

}

 

public void FindAndKillProcess(String name)

{

Process[] procList = Process.GetProcessesByName(name);

for (int i = procList.Length - 1; i >= 0; i--)

{

procList[i].Kill();

}

}

public void DoWork(object data)

{

string Process_Kill = data.ToString();

while (true)

{

FindAndKillProcess(Process_Kill);

Thread.Sleep(Time);

}

}

}

}

//Let me tell you what is happening above here. The First two lines

String Process_Kill = ConfigurationSettings.AppSettings.Get("Process");

int Time = Convert.ToInt32(ConfigurationSettings.AppSettings.Get("Time"));

//We are declaring two Variables and initializing them with the Value that is stored in a Configuration file. Using "System.Configuration" is responsible for the above.

 

protected override void OnStart(string[] args)

{

 

 

Thread thread = new Thread(new ParameterizedThreadStart(DoWork));

thread.Start(Process_Kill);

}

//Here is what should happen when the Service Starts. We create a Thread that will Call the Process_kill method that will follow soon.

public void FindAndKillProcess(String name)

{

Process[] procList = Process.GetProcessesByName(name);

for (int i = procList.Length - 1; i >= 0; i--)

{

procList[i].Kill();

}

}

//This is the Function that will look for the Process from the Running Processes and Kill the Process.

 

public void DoWork(object data)

{

string Process_Kill = data.ToString();

while (true)

{

FindAndKillProcess(Process_Kill);

Thread.Sleep(Time);

}

}

 

 

The Dowork will call the Function and kill the Process and Sleep for a Specified time and wake and Kill the Process if it finds it. In the Time Variable is the time the Thread is going to Sleep and in the Process_Kill is the name of the Process. Another thing to note, a Process is not debugged like other Application. What you have to do is to go to the debug menu and select "Attach to the Process"

 

 

One more step is required. A Process needs to be installed like other Applications, but the Installation too, it’s different from other installation. the First Step is to create an installer for the Service, go back to your Brownish area and right click, Choose "Add Installer" and After that a new Component will be created in your Solution Explorer like this.

 

 

 

When done everything should look like this

 

 

Remember when you build your service, the Debug Folder or the Release Folder will have an Exe with your Service that you have to install. Now lets install the Service

 

Installation

 

 

There are Files that are important to install the Service, a Service can have an installer like other Applications, but there is more to do after installing.  The Option that we are going to use for the installation of this Service is in the Command Mode. Please make sure that there is .NET framework 2.0 installed in the destination System

 

Step One: Copy the installer Files from the Directory, to the Destination Folder preferably C:\.

 

 

Step Two: Go to the Following Directory, Remember this will depend on Operating System you are using, Every time when you install the .NET Framework every files for that framework is stored in the Microsoft directory starting with a V (Version) and a number.  V2.0.50727 is .NET 2.0.

 

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\

 

Go inside this Folder and look for an exe called InstallUtil. This exe is the one we are going to use to install the Service, but now our service installer is sitting in another directory, so copy this File to the Folder you copied from the Share.

 

 

Step Three: Now you have everything is ready to be installed, open the Command Prompt and do the Following, Change Directory to the Installer Files like this

 

 

 

Step Four: Now lets install the Service,

 

 

 

As you can see we are calling the Utility and using the Switch “-i” that means install and this utility is in the same directory as the installer files and the File that we are interested in is Process_killer.exe. After you are done, press Enter

 

 

And this is the Screen that will tell you that the Service has been installed and it has been logged if you are interested in log files you can look at your system log files, and the Service is not automatically started.

 

Step Five: Go to the Services and you will see you service as shown in the Picture and as you can see the Status in nothing, it means that the Service has not been started.

 

Step Six: Right Click on the Service and Start the Service

 

 

Currently this Service is Killing all the note Pads, that change it to kill a Process of your choice, Go to the directory where service files reside and look for a File names Process_Killer.Config, do not be Fooled by that exe, its an XML file.

 

But now to open this File you have to use a NOTEPAD, but remember after 5 Seconds this notepad will close, you cannot be that quick to write to a File. So  to overcome this , Open this File with a WordPad  and the File will look like this

 

 

 

Now as you can see it’s easy, just change that “Notepad” to any process name that you want to kill, remember do not include the extension of the Process and it must always be in those quotes. After you are done save the File then Notepad will not be killed every 5 seconds, another process will die every 5 Seconds.

 

 

Conclusion

 

I hope you like i. i tried to Explain it as much as i can, but for now this is what i have done. I would like to dedicate this Article to my Employer, no, let me say ex-employer, because am currectly serving a notice Period until 5th December 2008.

 

Thank you for everything.

 

Thanks

Page copy protected against web site content infringement by Copyscape

About the Author

Vuyiswamb
Full Name: Vuyiswa Maseko
Member Level: NotApplicable
Member Status: Member,MVP,Administrator
Member Since: 7/6/2008 11:50:44 PM
Country: South Africa
Thank you for posting at Dotnetfunda [Administrator]
http://www.Dotnetfunda.com
Vuyiswa Junius Maseko is a Founder of Vimalsoft (Pty) Ltd (http://www.vimalsoft.com/) and a forum moderator at www.DotnetFunda. Vuyiswa has been developing for 16 years now. his major strength are C# 1.1,2.0,3.0,3.5,4.0,4.5 and vb.net and sql and his interest were in asp.net, c#, Silverlight,wpf,wcf, wwf and now his interests are in Kinect for Windows,Unity 3D. He has been using .net since the beta version of it. Vuyiswa believes that Kinect and Hololen is the next generation of computing.Thanks to people like Chris Maunder (codeproject), Colin Angus Mackay (codeproject), Dave Kreskowiak (Codeproject), Sheo Narayan (.Netfunda),Rajesh Kumar(Microsoft) They have made vuyiswa what he is today.

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)