ubuntu - 如何杀死在 Windows、Linux 和 MacOS 中特定端口上运行的进程 - C# (.Net Core)

标签 ubuntu process port kill windows-process

我需要 使用端口 的进程8001 Windows、Ubuntu 和 MacOS 在通过 C# 代码启动我的应用程序之前,因为我的应用程序需要使用 8001 在所有平台上。

所以请为我提供这个问题的解决方案。

最佳答案

这是 C# 中的代码示例

使用系统;
使用 System.Diagnostics;
使用 System.Collections.Generic;
使用 System.Text.RegularExpressions;
命名空间解决方案
{
公共(public)枚举平台
{
UNIX,赢
}

public class ProcessUtils
{

    public const string UNIX_PID_REGX = @"\w+\s+(\d+).*";
    public const string WIND_PID_REGX = @".*\s+(\d+)";

    public static void Main(string[] args) {
        Console.WriteLine("Hello World!");

        if (args !=  null && args.Length == 1) {
            findAndKillProcessRuningOn(port: args[0]);
        } else {
            Console.WriteLine("Illegal port option");
        }
    }

    public static void findAndKillProcessRuningOn(string port) {
        List<string> pidList = new List<string>();
        List<string> list = new List<string>();
        switch (getOSName())
        {
            case Platform.UNIX:
                list = findUnixProcess();
                list = filterProcessListBy(processList: list, filter: ":" + port);

                foreach(string pidString in list) {
                    string pid = getPidFrom(pidString: pidString, pattern: UNIX_PID_REGX);

                    if(!String.IsNullOrEmpty(pid)) {
                        pidList.Add(pid);
                    }
                }
                break;

            case Platform.WIN:
                list = findWindowsProcess();
                list = filterProcessListBy(processList: list, filter: ":" + port);

                foreach (string pidString in list)
                {
                    string pid = getPidFrom(pidString: pidString, pattern: WIND_PID_REGX);

                    if (!String.IsNullOrEmpty(pid))
                    {
                        pidList.Add(pid);
                    }
                }
                break;
            default:
                Console.WriteLine("No match found");
                break;
        }

        foreach(string pid in pidList) {
            killProcesBy(pidString: pid);
        }
    }

    public static Platform getOSName() {
        string os = System.Environment.OSVersion.VersionString;
        Console.WriteLine("OS = {0}", os);

        if (os != null && os.ToLower().Contains("unix")) {
            Console.WriteLine("UNXI machine");
            return Platform.UNIX;
        } else {
            Console.WriteLine("Windows machine");
            return Platform.WIN;
        }
    }

    public static void killProcesBy(string pidString) {
        int pid = -1;
        if(pidString !=  null && int.TryParse(s: pidString, result: out pid)){
            Process p = Process.GetProcessById(pid);
            p.Kill();
            Console.WriteLine("Killed pid =" + pidString);
        } else {
            Console.WriteLine("Process not found for pid =" + pidString);
        }

    }

    public static List<String> findUnixProcess() {
        ProcessStartInfo processStart = new ProcessStartInfo();
        processStart.FileName = "bash";
        processStart.Arguments = "-c lsof -i";

        processStart.RedirectStandardOutput = true;
        processStart.UseShellExecute = false;
        processStart.CreateNoWindow = true;

        Process process = new Process();
        process.StartInfo = processStart;
        process.Start();

        String outstr  = process.StandardOutput.ReadToEnd();

        return splitByLineBreak(outstr);
    }

    public static List<String> findWindowsProcess()
    {
        ProcessStartInfo processStart = new ProcessStartInfo();
        processStart.FileName = "netstat.exe";
        processStart.Arguments = "-aon";

        processStart.RedirectStandardOutput = true;
        processStart.UseShellExecute = false;
        processStart.CreateNoWindow = true;

        Process process = new Process();
        process.StartInfo = processStart;
        process.Start();

        String outstr = process.StandardOutput.ReadToEnd();

        return splitByLineBreak(outstr);
    }

    public static List<string> splitByLineBreak(string processLines)
    {
        List<string> processList = new List<string>();

        if (processLines != null)
        {
            string[] list = processLines.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
            processList.AddRange(collection: list);
        }

        return processList;
    }

    public static List<String> filterProcessListBy(List<String> processList, 
                                               String filter) {

        if(processList == null) {
            return new List<string>();
        }

        if(filter == null) {
            return processList;
        }

        return processList.FindAll(i => i != null && i.ToLower().Contains(filter.ToLower()));
    }

    public static String getPidFrom(String pidString, String pattern) {
        MatchCollection matches = Regex.Matches(pidString, pattern);

        if(matches != null && matches.Count > 0) {
            return matches[0].Groups[1].Value;
        }

        return "";
    }
}

}

关于ubuntu - 如何杀死在 Windows、Linux 和 MacOS 中特定端口上运行的进程 - C# (.Net Core),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51587273/

相关文章:

python - 为什么我不能绘制选定的点?

java - Tomcat无法连接8005端口

python - 杀死子进程,并在没有 psutil 或 subprocess 的情况下获取子进程 pid

javascript - 如何在 Node.js 中组织多进程应用程序?

c - 终止进程树(Windows 的 C)

c++ - 我从源代码安装了 GCC 5.2,但我不知道如何在 Ubuntu 15.04 上卸载它

mysql - 如何测试MySQL在哪个端口上运行以及是否可以连接?

python - 是否有关于使用 python 进行端口转发的简单描述?

linux - 找不到要编辑的 etc/default/tomcat7 AUTHBIND=YES

java - JDBC 连接 : How to specify the port for data-transfer?