写个软件来防止服务器网站CPU百分百

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Diagnostics;

namespace IISCpuForServer
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("监控IIS CPU w3wp 进程中,若100%,而自动结束该进程...");
            Thread thread new Thread(new ThreadStart(Run));
            thread.IsBackground true;
            thread.Start();
            Console.Read();
        }
        static void Run()
        {
            try
            {
                while (true)
                {
                    Process[] procs = Process.GetProcessesByName("w3wp");//读取网站的进程
                    if (procs != null && procs.Length > 0)
                    {

                        foreach (Process pro in procs)
                        {
                            if (!pro.HasExited)
                            {
                                CheckPro(pro);
                            }
                        }
                    }
                    Thread.Sleep(TimeSpan.FromMinutes(5));//5分钟来一次。
                }
            }
            catch (Exception err)
            {
                Console.WriteLine(err.Message);
            }
        }
        static void CheckPro(Process pro)
        {
            int s = 0;//60秒。
            int killTimes = 0;
            //间隔时间(毫秒)
            int interval = 1000;
            //上次记录的CPU时间
            TimeSpan prevCpuTime = TimeSpan.Zero;
            while (true)
            {
                //当前时间
                TimeSpan curTime = pro.TotalProcessorTime;
                //间隔时间内的CPU运行时间除以逻辑CPU数量
                double value = (curTime - prevCpuTime).TotalMilliseconds / interval / Environment.ProcessorCount * 100;
                prevCpuTime = curTime;

                if (s > 0)
                {
                    if (value > 90 && value < 100)//cpu连续超过90% 50秒就杀。
                    {
                        killTimes++;
                        if (killTimes > 50)
                        {
                            Console.WriteLine(pro.Id " 长期高CPU,秒杀...");
                            pro.Kill();
                            Thread.Sleep(TimeSpan.FromMinutes(3));
                            return;
                        }
                    }
                    else
                    {
                        killTimes 0;
                    }
                    if (killTimes > 0)//只有cpu超过90%才打印文字
                    {
                        Console.WriteLine(pro.Id " CPU:" + value + " -- killtimes:" + killTimes);
                    }
                }
                Thread.Sleep(interval);
                if (s > 59)
                {
                    s = -1;
                    break;
                }
                else
                {
                    s++;
                }
            }
        }

    }
}

 

posted @ 2020-09-23 18:46  net5x  阅读(87)  评论(0)    收藏  举报