123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269 |
- using Newtonsoft.Json;
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Net.NetworkInformation;
- using System.Runtime.InteropServices;
- using System.Threading;
- using Vinno.IUS.Common.Log;
- namespace ProcessDaemonTool
- {
- class Program
- {
- private static List<ProtectProgress> _needProtectProcessList = new List<ProtectProgress>();
- private static SpinThread _spinThread;
- static void Main(string[] args)
- {
- WriteInfo("Start....ProcessDaemonTool ");
- var successed= DisableShowErrorUIHelper.SetDontShowUI();
- WriteInfo($"{successed}, set disable show error UI for regedit");
- Process curProcess = System.Diagnostics.Process.GetCurrentProcess();
- //only one cmd on the same time
- if (Process.GetProcesses().Any(x => x.ProcessName == curProcess.ProcessName && x.Id != curProcess.Id))
- {
- return;
- }
- AppManager.Instance.Initialize();
- if (!initNeedProtectProcess())
- {
- return;
- }
-
- _spinThread = new SpinThread("StartProtect", TimeSpan.FromSeconds(AppManager.Instance.Config.Interval), StartProtect);
- _spinThread.Start();
- WriteInfo("Successed ProcessDaemonTool ");
- Console.ReadLine();
- }
- private static bool initNeedProtectProcess()
- {
- var appSettings = AppManager.Instance.Config.Process;
- if (appSettings.Count == 0)
- {
- WriteTitle("No Found Check Process For Setting");
- return false;
- }
- foreach (var setting in appSettings)
- {
- string name = setting.Key;
- var protectProgress = new ProtectProgress()
- {
- Description = name,
- Command = setting.Value,
- ProtectCount = 0,
- StartupMode= setting.StartupMode,
- IsCheckProcessName= setting.IsCheckProcessName,
- CheckPort= setting.CheckPort,
- EnableCheckProcess= setting.EnableCheckProcess
- };
- var existProcessArray = Process.GetProcessesByName(setting.ProcessName);
- if(existProcessArray != null&& existProcessArray.Length>0)
- {
- protectProgress.Process = existProcessArray.FirstOrDefault();
- }
- _needProtectProcessList.Add(protectProgress);
- }
- var descriptions = _needProtectProcessList.Where(v => v.Process != null)?.Select(v => "Attach To Process:" + v.Description + " "+v.Command).ToList();
- if(descriptions.Count>0)
- {
- WriteInfo(descriptions);
- }
- else
- {
- WriteSucceed(_needProtectProcessList.Select(x => $" Load setting Process: {x.Description} {x.Command}\n").ToList());
- }
- return true;
- }
- private static void StartProtect(object o)
- {
- try
- {
- //一些没有初始化的可以初始化了
- Process[] processIdAry = Process.GetProcesses();
- foreach (ProtectProgress protectProgress in _needProtectProcessList)
- {
- if (!string.IsNullOrEmpty(protectProgress.CheckPort))
- {
- var isUsed = PortInUse(int.Parse(protectProgress.CheckPort));
- if (isUsed)
- {
- continue;
- }
- }
- if (protectProgress.Process != null&&!protectProgress.EnableCheckProcess)
- {
- continue;
- }
- //说明已经启动了
- if (protectProgress.Process != null && processIdAry.Any(x => x.Id == protectProgress.Process.Id))
- {
- var exist = processIdAry.FirstOrDefault(v => v.ProcessName.Contains(protectProgress.Description));
- continue;
- }
- if (protectProgress.IsCheckProcessName)
- {
- var existProcessArray = Process.GetProcessesByName(protectProgress.Description);
- if (existProcessArray != null && existProcessArray.Length > 0)
- {
- protectProgress.Process = existProcessArray.FirstOrDefault();
- continue;
- }
- }
- try
- {
- string log1 = $"Check Process Exited: {protectProgress.Description}";
- Logger.WriteLineInfo(log1);
- protectProgress.Process = startCmd(protectProgress.Command, protectProgress.StartupMode== StartupMode.cmd);
- if (protectProgress.Process != null)
- {
- string log = $"Start Process successed: {protectProgress.Description}, Id:{protectProgress.Process.Id}, Name:{protectProgress.Process.ProcessName} ,RetryNum:{protectProgress.ProtectCount} ";
- Logger.WriteLineInfo(log);
- WriteSucceed(log);
- protectProgress.ProtectCount++;
- protectProgress.Name = protectProgress.Process.ProcessName;
- }
- }
- catch (Exception ex)
- {
- string log = $"Start Process Failed {protectProgress.Description},Command:{protectProgress.Command} ,ex:{ex}";
- Logger.WriteLineError(log);
- WriteError(log);
- }
- Thread.Sleep(3000);
- }
- }
- catch (Exception exception)
- {
- Console.WriteLine(exception);
- throw;
- }
- finally
- {
- GC.Collect();
- }
- }
- private static Process startCmd(string cmd,bool useShellExecute=true)
- {
- cmd = cmd.Replace("|", "&&");
- var processStartInfo = new ProcessStartInfo("cmd.exe", "/c " + cmd);
- processStartInfo.Verb = "runas";
- processStartInfo.CreateNoWindow = false;
- processStartInfo.UseShellExecute = useShellExecute;
- // processStartInfo.RedirectStandardOutput = true;
- Process p = Process.Start(processStartInfo);
- return p;
- }
- private static bool PortInUse(int port)
- {
- bool inUse = false;
- IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
- IPEndPoint[] ipEndPoints = ipProperties.GetActiveTcpListeners();
- foreach (IPEndPoint endPoint in ipEndPoints)
- {
- if (endPoint.Port == port)
- {
- inUse = true;
- break;
- }
- }
- return inUse;
- }
- [DllImport("user32.dll", CharSet = CharSet.Auto)]
- public static extern IntPtr SendMessageTimeout(
- HandleRef hWnd,
- int msg,
- IntPtr wParam,
- IntPtr lParam,
- int flags,
- int timeout,
- out IntPtr pdwResult);
- const int SMTO_ABORTIFHUNG = 2;
- public static bool RespondingWithinMs(Process process, int timeoutMs)
- {
- IntPtr ptr2;
- return SendMessageTimeout(
- new HandleRef(process, process.MainWindowHandle),
- 0,
- IntPtr.Zero,
- IntPtr.Zero,
- SMTO_ABORTIFHUNG,
- timeoutMs,
- out ptr2) != IntPtr.Zero;
- }
- #region write
- private static void WriteTitle(string text)
- {
- WriteTitle(new List<string>() { text });
- }
- private static void WriteSucceed(List<string> textList)
- {
- textList.ForEach(Console.WriteLine);
- }
- private static void WriteSucceed(string text)
- {
- text = $"[{DateTime.Now:yyyyMMddHHmmss},{DateTime.Now.Millisecond:d3}]-" + "[Thread:" + Thread.CurrentThread.ManagedThreadId.ToString() + "]" + text;
- Console.WriteLine(text);
- }
- private static void WriteInfo(string text)
- {
- text = $"[{DateTime.Now:yyyyMMddHHmmss},{DateTime.Now.Millisecond:d3}]-" + "[Thread:" + Thread.CurrentThread.ManagedThreadId.ToString() + "]" + text;
- Console.WriteLine(text);
- }
- private static void WriteInfo(List<string> textList)
- {
- textList.ForEach(Console.WriteLine);
- }
- private static void WriteWarn(string text)
- {
- text = $"[{DateTime.Now:yyyyMMddHHmmss},{DateTime.Now.Millisecond:d3}]-" + "[Thread:" + Thread.CurrentThread.ManagedThreadId.ToString() + "]" + text;
- Console.WriteLine(text);
- }
- private static void WriteWarn(List<string> textList)
- {
- textList.ForEach(Console.WriteLine);
- }
- private static void WriteError(string text)
- {
- text = $"[{DateTime.Now:yyyyMMddHHmmss},{DateTime.Now.Millisecond:d3}]-" + "[Thread:" + Thread.CurrentThread.ManagedThreadId.ToString() + "]" + text;
- Console.WriteLine(text);
- }
- private static void WriteError(List<string> textList)
- {
- textList.ForEach(Console.WriteLine);
- }
- private static void WriteTitle(List<string> textList)
- {
- WriteSplitLine();
- textList.ForEach(Console.WriteLine);
- WriteSplitLine();
- }
- private static void WriteSplitLine()
- {
- Console.WriteLine("=======================================");
- }
- #endregion
- }
- }
|