How to kill process that run on specific port in Windows,Linux and MacOS - C# (.Net Core)

osx what is running on port
kill process on port
find process running on port
macos kill port 3000
find running on port
kill port 8080
kill port 8000
kill port mac

I need to kill process that uses port 8001 in Windows,Ubuntu and MacOS before starting my application via C# Code,because my application is need to use 8001 on all platform.

So Please Provide me Solution for this problem.

Here is the code sample in C#

using System; using System.Diagnostics; using System.Collections.Generic; using System.Text.RegularExpressions; namespace Solution { public enum Platform { UNIX, WIN }

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 "";
    }
}

}

Process.Kill Method (System.Diagnostics), The Kill method forces a termination of the process, while CloseMainWindow only requests a termination. Therefore, the request to exit the process by closing the main window does You can call Kill and CloseMainWindow only for processes that are running on the local computer. NET Core. 3.1 3.0 2.2 2.1 2.0 1.1 1.0  I need to kill process that uses port 8001 in Windows,Ubuntu and MacOS before starting my application via C# Code,because my application is need to use 8001 on all platform. So Please Provide me Solution for this problem.

dotnet run command, Allows the command to stop and wait for user input or action (for example, to complete authentication). Available since .NET Core 3.0 SDK. --  The port is put into TIME_WAIT state after the parent process is killed. The OS will then eventually completely close the port after about 60 seconds. It means that you can't reuse the port for at least 60 seconds (unless you give the reuse option to the socket). i use linux and i get bash: fuser: command not found.

On macOS and Linux

This way you dont have to know the PID ;)

sudo kill -9 $(netstat -vanp tcp | grep 8001 | grep -v grep | awk '{print $9}')

Finding the pid listening on a specific port on Mac OS X, I've recently switched from Linux to Mac OS X and I'm trying to get used to the One of the differences from Linux is the way to find the process id (pid) listening on a specific port. On Max OS X how ever you'll run into the following error message: Previous PostCapistrano and Net:SSH with login shell. A one-liner to extract the PID of the process using port 3000 and kill it. The -t flag removes everything but the PID from the lsof output, making it easy to kill it. You can use lsof -i:3000. That is "List Open Files". This gives you a list of the processes and which files and ports they use.

Getting started with .NET for Linux, NET Core open source means it's time for Linux developers to get comfortable and start If they use Windows, the language list includes C#, JavaScript, and TypeScript. Windows, Linux, MacOS, and even a television OS: Samsung's Tizen. When you run dotnet run, the process that runs is dotnet. What do you do? You kill the process. But how? Believe it or not, your best bet most often lies within the command line. Thankfully, Linux has every tool necessary to empower you, the user, to kill an errant process. However, before you immediately launch that command to kill the process, you first have to know what the process is.

Build and run an ASP.NET Core app in a container, NET Core app in a Docker container, using Visual Studio Code. Wait for the C# extension to prompt you to add required assets for build and debug, and choose Yes. Choose Windows or Linux when prompted to choose the operating system. You can use specific port on the host by changing the Docker run options  Linux: How to list and kill a process using a port - kill_port_process.sh

Developing inside a Container using Visual Studio Code Remote , Other glibc based Linux containers may work if they have needed Windows / macOS: If you run into trouble, see Docker Desktop for Windows tips on avoiding common vscode-remote-try-python your-python-project-here go dotnet install an extension, or forward a port, a local image-specific configuration file  Start processes from C# in DotNet Core. Being able to run batch during the lifecycle of an application is always useful. It gives a way to programmatically interact with any programs which implements a CLI. Today we will see how we can start processes from C# on .NET Core applications and how it can be useful in a real scenario. 1. Unzip from

Comments
  • download sample project from github.com/ganesara/processKill.git
  • bash -c lsof -i returns all process and so slow on mac
  • Thanks @ramanathan-ganesan , but how i implement in c# Programming ?