• C#检查服务状态,以及进行服务启停


    1. linux环境

    linux环境通过执行bash命令直接执行:

    public string RunCmdLinux(string cmd)
            {
                var proc = new Process();
                System.Console.Write($"Run Linux cmd ==> [{cmd}]   START!");
                proc.StartInfo.CreateNoWindow = true;
                proc.StartInfo.FileName = "/bin/bash";
                proc.StartInfo.UseShellExecute = false;
                proc.StartInfo.RedirectStandardError = true;
                proc.StartInfo.RedirectStandardInput = true;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.Start();
                proc.StandardInput.WriteLine(cmd);
                proc.StandardInput.WriteLine("exit");
                string outStr = proc.StandardOutput.ReadToEnd();
                proc.Close();
                System.Console.Write($"Run Linux cmd ==> [{cmd}]   FINISHED!");
                return outStr;
            }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    2. window环境

    windows使用 System.ServiceProcess依赖下的ServiceController进行操作,具体代码:

            /// <summary>
            /// 开启windows服务
            /// </summary>
            /// <param name="serviceName"></param>
            /// <returns></returns>
    
            public bool StartWindowsService(string serviceName)
            {
                bool isbn = false;
                try
                { 
                    ServiceController star_service = new ServiceController(serviceName);
                    if (star_service.Status != ServiceControllerStatus.Running &&
                    star_service.Status != ServiceControllerStatus.StartPending)
                    {
                        star_service.Start();
    
                        for (int i = 0; i < 60; i++)
                        {
                            star_service.Refresh();
                            System.Threading.Thread.Sleep(1000);
                            if (star_service.Status == ServiceControllerStatus.Running)
                            {
                                isbn = true;
                                break;
                            }
                            if (i == 59)
                            {
                                isbn = false;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    System.Console.Write("[StartWindowsService] Error", ex);
                    return false;
                }
                System.Console.Write($"[StartWindowsService]_serviceName:{serviceName},status:{isbn}");
                return isbn;
            }
    
            /// <summary>
            /// 关闭windows服务
            /// </summary>
            /// <param name="serviceName"></param>
            /// <returns></returns>
            public bool StopWindowsService(string serviceName)
            {
                bool isbn = false;
                try
                {
                    ServiceController star_service = new ServiceController(serviceName);
                    System.Console.WriteLine(star_service.Status);
                    if (star_service.Status == ServiceControllerStatus.Running)
                    {
                        star_service.Stop();
                    }
                    for (int i = 0; i < 60; i++)
                    {
                        star_service.Refresh();
                        System.Threading.Thread.Sleep(1000);
                        if (star_service.Status == ServiceControllerStatus.Running)
                        {
                            isbn = true;
                            break;
                        }
                        if (i == 59)
                        {
                            isbn = false;
                        }
                    }
                }
                catch (Exception ex)
                {
                    System.Console.Write("[StopWindowsService] Error", ex);
                    isbn = false;
                }
                System.Console.Write($"[StopWindowsService]_serviceName:{serviceName},status:{isbn}");
                return isbn;
            }
    
            /// <summary>
            /// 获取windows服务的状态
            /// </summary>
            /// <param name="serviceName">服务名</param>
            /// <returns>服务的状态</returns>
            public string CheckWindowsServiceStatus(string serviceName) {
                var services = ServiceController.GetServices();
                string serviceStatu = string.Empty;
                bool isServiceExist = false;
                foreach (var s in services)
                {
                    if (s.ServiceName.ToLower().Equals(serviceName.ToLower()))
                    {
                        System.Console.Write($"[CheckWindowsServiceStatus] serviceName:{serviceName},serviceStatus:{s.Status}");
                        isServiceExist = true;
                        serviceStatu = s.Status.ToString();
                        break;
                    }
                }
    
                if (!isServiceExist)
                {
                    System.Console.Write($"[CheckWindowsServiceStatus] serviceName:${serviceName} not instal");
                    serviceStatu = "Service is not installed";
                }
                return serviceStatu;
            }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109

    当服务不能停止时,还可根据服务名,通过进程进行杀死:

     /// <summary>
            /// 通过服务的名称查询进程号,进行杀死
            /// </summary>
            /// <param name="threadName">服务名称</param>
            /// <returns></returns>
            public void ThreadKillExitis(string threadName)
            { 
                Process[] processList = Process.GetProcesses();
                foreach (Process process in processList)
                {
                    if (process.ProcessName.ToLower() == threadName.ToLower())
                    {
                        process.Kill(); 
                    }
                }
                System.Console.Write($"[ThreadKillExitis]_{threadName} 成功");
            }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    权限配置:

    由于windows环境运行需要获取系统权限,因此需要设置app.manifest内容。
    首先右键项目->属性->安全性下勾选启用ClickOnce安全设置,会默认增加一个app.manifest文件。
    在这里插入图片描述
    打开后,将修改为

    在这里插入图片描述
    完成后,右键项目->属性->安全性下取消勾选启用ClickOnce安全设置

  • 相关阅读:
    Zookeeper面试点深入剖析
    基于STM32的简化版智能手表
    Istio网关流量转发
    Flink Java 之 Watermark(触发原理, 使用)
    粗糙集知识约简的python代码
    【吞噬星空】罗峰成功抵达虬龙星,宇宙超级富二代登场,不容错过
    GIS开发入门,TopoJSON格式是什么?TopoJSON格式与GeoJSON格式有什么不同?
    代码随想录刷题|LeetCode 583. 两个字符串的删除操作 72. 编辑距离 编辑距离总结篇
    Jupyter如何开启Debug调试功能
    C# .Net AOP 演进历史POP OOP 代码细节篇
  • 原文地址:https://blog.csdn.net/github_38924695/article/details/134433111