windows服务

 
 
 
 
Windows 服务
 
 
一. Windows 服务介绍:
服务是一个或一组进程,它通过向其他程序提供支持,从而增加了Windows的功能。服务程序是一个后台程序,在后台运行。
 
一个 Windows 服务程序是在 Windows 操作系统下能完成特定功能的可执行的应用程序。 Windows 服务程序虽然是可执行的,但是它不像一般的可执行文件通过双击就能开始运行了,它必须有特定的启动方式。这些启动方式包括了 自动启动和手动启动 两种。
 
对于 自动启动 Windows 服务程序,它们在 Windows 启动或是重启之后用户登录之前就开始执行了。只要你将相应的 Windows 服务程序注册到服务控制管理器( Service Control Manager )中,并将其启动类别设为自动启动就行了。
 
而对于 手动启动 Windows 服务程序,你可以通过命令行工具的 NET START 命令来启动它,或是通过控制面板中管理工具下的服务一项来启动相应的 Windows 服务程序(见图 1 )。
 
同样,一个 Windows 服务程序也不能像一般的应用程序那样被终止。因为 Windows 服务程序一般是没有用户界面的,所以你也要通过命令行工具或是下面图中的工具来停止它,或是在系统关闭时使得 Windows 服务程序自动停止。因为 Windows 服务程序没有用户界面,所以基于用户界面的 API 函数对其是没有多大的意义。
 

为了能使一个Windows服务程序能够正常并有效的在系统环境下工作,程序员必须实现一系列的方法来完成其服务功能。Windows服务程序的应用范围很广,典型的Windows服务程序包含了硬件控制、应用程序监视、系统级应用、诊断、报告、Web和文件系统服务等功能。

  图

 

 

 

 二.创建Windows服务程序:
创建 Windows 服务程序的一般步骤:
1 编写 OnStart() OnStop() 等事件处理程序。
2 添加安装程序
3 注册服务
4 启动或停止服务
 
.Net 框架下与 Windows 服务相关的命名空间和其中的类库。 .
 System.ServiceProcess

 System.Diagnostics

要创建一个最基本的Windows服务程序,我们只需要运用.Net框架下的System.ServiceProcess命名空间以及其中的四个类:ServiceBaseServiceInstallerServiceProcessInstaller以及ServiceController,其体系结构可见图2

  图2


 

1 ServiceBase
为将作为服务应用程序的一部分而存在的服务提供基类。在创建新的服务类时,必须从 ServiceBase 派生。
   ServiceBase 类定义了一些可被其子类重载的方法,通过这些重载方法,服务控制管理器就可以控制该 Windows 服务程序了。
ServiceBase
类主要重载方法:
1 OnStart ():服务开始时执行
2 OnStop ():服务停止时执行
3 OnPause ():服务暂停时执行
4 OnContinue ():服务继续执行时执行
5 OnCustomCommand ():用来完成一些特定的操作。

ServiceBase 类主要属性:
(1)         Autolog :是否自动写入系统的日志文件
(2)         CanShutdown :服务是否在运行它的计算机关闭时收到通知,以便能够调用 OnShutDown 过程
(3)         ServiceName :指定了Windows服务的名称。
(4)         CanPauseAndContinue :服务是否接受暂停或继续运行的请求
(5)         CanStop :允许停止服务。


  要使得一个Windows服务程序能够正常运行,我们需要像创建一般应用程序那样为它创建一个程序的入口点。在Windows服务程序中,我们也是在Main()函数中完成这个操作的。首先我们在Main()函数中创建一个Windows服务的实例,该实例应该是ServiceBase类的某个子类的对象,然后我们调用由基类ServiceBase类定义的一个Run()方法。然而Run()方法并不就开始了Windows服务程序,我们必须通过前面提到的服务控制管理器调用特定的控制功能来完成Windows服务程序的启动,也就是要等到该对象的OnStart()方法被调用时服务才真正开始运行。如果你想在一个Windows服务程序中同时启动多个服务,那么只要在Main()函数中定义多个ServiceBae类的子类的实例对象就可以了,方法就是创建一个ServiceBase类的数组对象,使得其中的每个对象对应于某个我们已预先定义好的服务。
 
2 ServiceInstaller
 
安装一个 ,该类扩展 ServiceBase 来实现服务。 在安装服务应用程序时由安装实用工具调用该类。
ServiceInstaller 执行特定于其所关联服务的操作。它由安装实用工具用来将与服务关联的注册表值写入 HKEY_LOCAL_MACHINE/System/CurrentControlSet/Services 注册表项内的子项。服务由它在该子键内的“服务名”(ServiceName) 标识。该子键还包含服务所属的可执行文件或 .dll 的名称。
若要安装服务,请创建从 Installer 类继承的项目安装程序类,并将该类的 RunInstallerAttribute 属性设置为 true。
 
ServiceInstaller 类主要属性:
(1)Description:在图3中显示的“描述”文字。
(2)DisplayName: 在图3中显示的服务名称
(3)ServiceName:指定服务名称。与 ServiceBase 类中的 ServiceName 名字相同
(4)StartType:指定windows服务的启动类型。启动类型有:
        a. Manual      服务安装后,必须手动启动。
         b. Automatic    每次计算机重新启动时,服务都会自动启动。
         c. Disabled     服务无法启动。
图3
 
 
3 ServiceProcessInstaller
安装一个 可执行文件 ,该文件包含扩展 ServiceBase 的类 。该类由安装实用工具(如 InstallUtil.exe )在安装服务应用程序时调用。
 
ServiceProcessInstaller 执行可执行文件中的所有服务的公共操作。安装实用工具使用它来写与要安装服务关联的注册表值。
 
ServiceProcessInstaller 类主要属性:
Account :指定运行此服务的帐户类型。LocalSystem 本地用户启动。
安装服务:
设置path=C:/WINDOWS/Microsoft.NET/Framework/v2.0.50727 或直接进入此目录运行installutil   D:/Study/MywinService/MywinService/bin/Debug/MywinService.exe
 
卸载服务:
installutil /u D:/Study/MywinService/MywinService/bin/Debug/MywinService.exe
 
启动服务:
net start [ ServiceInstaller 类DisplayName的名称 ]
 
如上所示:net start TestService
 
停止服务:
Net stop  [ ServiceInstaller 类DisplayName的名称 ]
如上所示:net stop TestService
 
 
分析生成的代码:
1 Service1 类: 该类继承于System.ServiceProcess.ServiceBase基类。
 
2 Main() 方法: 构成Windows服务的入口点。
 
3 OnStart() 方法和OnStop()方法: 这两个方法位于ServiceBase基类中,并由服务程序(Service1类)继承,当启动或停止该服务时,服务控制管理器将分别调用这两个方法。
 
3         Service1() 构造方法: 担当新的Windows服务的服务main()方法。由于 Windows 服务 项目只包含一个服务应用程序。因此由Visual Studio .NET生成的Service1()方法就足够了。但是服务程序要求同一个服务应用程序有多个服务,则应创建多个服务main(0方法并向服务控制管理器进行注册。
 
4         该应用程序的服务main()方法向服务控制管理器注册所有main方法(在该示例中为Service1()方法)
 
5         Run() 方法:是ServiceBase类的重载static Run()方法,它为服务提供主入口点。它将指定的服务加载到内存中,而不启动服务。通过OnStart()和OnStop()来启动或停止服务。
 
示例代码分析:
Program.cs 代码如下:
 
using System.Collections.Generic;
using System.ServiceProcess;
using System.Text;
 
namespace MywinService
{
    static class Program
    {
        ///<summary>
        /// 应用程序的主入口点。
        ///</summary>
        static void Main()
        {
            ServiceBase[] ServicesToRun;
 
            // 同一进程中可以运行多个用户服务。若要将
            // 另一个服务添加到此进程中,请更改下行以
            // 创建另一个服务对象。例如,
            //
            //   ServicesToRun = new ServiceBase[] {new Service1(), new MySecondUserService()};
            //
            ServicesToRun = new ServiceBase[] { new Service1() };
 
            ServiceBase.Run(ServicesToRun);
        }
    }
}
Service1.cs 代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.IO;
 
namespace winService
{
    public partial class Service1 : ServiceBase
    {
        public Service1()
        {
            InitializeComponent();
        }
 
    protected override void OnStart(string[] args)
        {
            // TODO: 在此处添加代码以启动服务。
        }
 
        protected override void OnStop()
        {
            // TODO: 在此处添加代码以执行停止服务所需的关闭操作。
        }
    }
}
  
单个服务的示例:
此项目下载位置:http://download.csdn.net/source/367827
// Service1.cs代码如下:
using  System;
using  System.Collections.Generic;
using  System.ComponentModel;
using  System.Data;
using  System.Diagnostics;
using  System.ServiceProcess;
using  System.Text;
using  System.IO;

namespace  MywinService
{
    
public partial class Service1 : ServiceBase
    
{
        
public Service1()
        
{
            InitializeComponent();
        }


         
///<summary>
         
///服务启动时执行
         
///</summary>
         
///<param name="args"></param>

        protected override void OnStart(string[] args)
        
{
             
//TODO: 在此处添加代码以启动服务。
            FileStream fs = new FileStream(@"c:log.txt", FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter sw 
= new StreamWriter(fs);
            sw.BaseStream.Seek(
0, SeekOrigin.End);
            sw.WriteLine(
"Service1启动时间为:" + DateTime.Now.ToString());
            sw.Flush();
            fs.Close();
        }


         
///<summary>
         
///服务停止时执行
         
///</summary>

        protected override void OnStop()
        
{
             
//TODO: 在此处添加代码以执行停止服务所需的关闭操作。
            FileStream fs = new FileStream(@"c:log.txt", FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter sw 
= new StreamWriter(fs);
            sw.BaseStream.Seek(
0, SeekOrigin.End);
            sw.WriteLine(
"Service1停止时间为:" + DateTime.Now.ToString());
            sw.Flush();
            fs.Close();
        }

    }

}


// Program.cs代码如下:
using  System.Collections.Generic;
using  System.ServiceProcess;
using  System.Text;

namespace  MywinService
{
    
static class Program
    
{
        
/// <summary>
        
/// 应用程序的主入口点。
        
/// </summary>

        static void Main()
        
{
            ServiceBase[] ServicesToRun;

            
// 同一进程中可以运行多个用户服务。若要将
            
// 另一个服务添加到此进程中,请更改下行以
            
// 创建另一个服务对象。例如,
            
//
            
//   ServicesToRun = new ServiceBase[] {new Service1(), new MySecondUserService()};
            
//
            ServicesToRun = new ServiceBase[] new Service1() };

            ServiceBase.Run(ServicesToRun);
        }

    }

}


多个服务的示例:
此项目下载位置:http://download.csdn.net/source/367828
// Service1.cs代码如下:
using  System;
using  System.Collections.Generic;
using  System.ComponentModel;
using  System.Data;
using  System.Diagnostics;
using  System.ServiceProcess;
using  System.Text;
using  System.IO;

namespace  MywinService
{
    
public partial class Service1 : ServiceBase
    
{
        
public Service1()
        
{
            InitializeComponent();
        }


         
///<summary>
         
///服务启动时执行
         
///</summary>
         
///<param name="args"></param>

        protected override void OnStart(string[] args)
        
{
             
//TODO: 在此处添加代码以启动服务。
            FileStream fs = new FileStream(@"c:log.txt", FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter sw 
= new StreamWriter(fs);
            sw.BaseStream.Seek(
0, SeekOrigin.End);
            sw.WriteLine(
"Service1启动时间为:" + DateTime.Now.ToString());
            sw.Flush();
            fs.Close();
        }


         
///<summary>
         
///服务停止时执行
         
///</summary>

        protected override void OnStop()
        
{
             
//TODO: 在此处添加代码以执行停止服务所需的关闭操作。
            FileStream fs = new FileStream(@"c:log.txt", FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter sw 
= new StreamWriter(fs);
            sw.BaseStream.Seek(
0, SeekOrigin.End);
            sw.WriteLine(
"Service1停止时间为:" + DateTime.Now.ToString());
            sw.Flush();
            fs.Close();
        }

    }

}


// Service2.cs代码如下:
using  System;
using  System.Collections.Generic;
using  System.ComponentModel;
using  System.Data;
using  System.Diagnostics;
using  System.ServiceProcess;
using  System.Text;
using  System.IO;

namespace  MywinService
{
    
partial class Service2 : ServiceBase
    
{
        
public Service2()
        
{
            InitializeComponent();
        }


        
protected override void OnStart(string[] args)
        
{
            
// TODO: 在此处添加代码以启动服务。
            
//启动批处理文件删除垃圾文件
            FileStream fs = new FileStream(@"c:log.txt", FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter sw 
= new StreamWriter(fs);
            sw.BaseStream.Seek(
0, SeekOrigin.End);
            sw.WriteLine(
"开始删除系统垃圾文件的时间为:" + DateTime.Now.ToString());
            sw.Flush();
            fs.Close();
            Process.Start(
@"D:StudyMywinServiceMywinServiceclear.bat");
            
        }


        
protected override void OnStop()
        
{
            
// TODO: 在此处添加代码以执行停止服务所需的关闭操作。
            Process[] process = Process.GetProcesses();
            FileStream fs 
= new FileStream(@"c:log.txt", FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter sw 
= new StreamWriter(fs);
            sw.BaseStream.Seek(
0, SeekOrigin.End);
            sw.WriteLine(
"删除系统垃圾文件完成的时间为:" + DateTime.Now.ToString());
            
//遍历系统进程,并直接杀掉名为cmd的进程.
            foreach (Process pro in process)
            
{
                
if (pro.ProcessName.Equals("cmd"== true)
                
{
                    pro.Kill();
                    sw.WriteLine(
"通出cmd模式时间为:" + DateTime.Now.ToString());
                }

            }

            sw.Flush();
            fs.Close();
        }

    }

}


// Process.cs代码如下:
using  System.ServiceProcess;
using  System.Text;

namespace  MywinService
{
    
static class Program
    
{
        
/// <summary>
        
/// 应用程序的主入口点。
        
/// </summary>

        static void Main()
        
{
            ServiceBase[] ServicesToRun;

            
// 同一进程中可以运行多个用户服务。若要将
            
// 另一个服务添加到此进程中,请更改下行以
            
// 创建另一个服务对象。例如,

            ServicesToRun 
= new ServiceBase[] new Service1(), new Service2() };
            

            ServiceBase.Run(ServicesToRun);
        }

    }

}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值