在通过C#代码启动我的应用程序之前,我需要kill在Windows、Ubuntu和MacOS中使用端口8001的进程,因为我的应用软件需要在所有平台上使用8001。
所以请给我这个问题的解决方案。
在macOS和Linux上
这样你就不必知道PID;(
sudo kill -9 $(netstat -vanp tcp | grep 8001 | grep -v grep | awk '{print $9}')
这是C#中的代码示例
using System; <br>
using System.Diagnostics; <br>
using System.Collections.Generic; <br>
using System.Text.RegularExpressions; <br>
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 "";
}
}
}
Windows
-
查找进程ID
- 命令
netstat -a -b
- 资源监视器来自(开始>>所有程序>>附件>>系统工具>>资源监视器(
- 命令
-
使用以下命令
taskkill /PID pid
终止进程
UNIX和MAC
- 使用
lsof -i | grep <process id>
查找进程ID - 使用命令
kill -9 <process id>
终止进程
手动终止每个进程
这里已经有一些很好的答案了,主要推荐使用sudo lsof -i :<port number>
查看在指定端口上运行的进程,然后对每个进程ID运行kill -9 <process id>
,以1比1杀死它们,从而找到进程ID的方法。
TLDR;
sudo lsof -i :<port number>
-列出端口上的进程kill -9 <process id>
——PID控制的压井过程
此方法的缺陷在于,必须首先确定PID列表,然后手动终止每个PID。这个脚本将允许您终止在给定端口上运行的所有进程,而无需查看PID:
终止端口上所有进程的脚本
#!bin/zsh
# Example Usage: pkill 3000
# Kills all processes listening on the specified port
pkill () {
sudo lsof -i :$1 | # get a list of all processes listening on the specified port
xargs -I % echo % | # convert the list into a string
awk '{print $2}' | # select only the PID column (2)
awk 'NR%2==0' | # remove the header PID
sort | # sort the PID list
awk '!a[$0]++' | # remove duplicate PIDs
xargs kill -9 # kill all the processes by their PIDs
}
或者,您可以只使用函数运行的脚本,但我希望看到pkill函数可以为每个管道命令的作用提供有用的解释。
单行版本
sudo lsof -i :$<process id> | xargs -I % echo % | awk '{print $2}' | awk 'NR%2==0' | sort | awk '!a[$0]++' | xargs kill -9
对于windows,您可以发现任何端口都是可用的或不可用的-->
检查端口8081是否空闲
• netstat -ano | findstr :8081
如果不是免费的,并且希望这适用于任何工作,那么上面会给你pid,使用下面的8081端口杀死旧的旧的
• taskkill /PID pid
对于mac和Ubuntu,请遵循-https://stackoverflow.com/a/57290177/17673102