要在C#中获取Linux系统的CPU、内存和磁盘使用状态,您可以使用System.Diagnostics命名空间中的Process类来执行Shell命令并获取输出。
以下是一个示例代码,演示如何获取这些信息:
using System;
using System.Diagnostics;
class Program
{
static void Main()
{
// 获取CPU使用率
string cpuUsageCommand = "top -bn1 | grep 'Cpu(s)' | awk '{print $2 + $4}'";
string cpuUsageOutput = ExecuteShellCommand(cpuUsageCommand);
Console.WriteLine(#34;CPU Usage: {cpuUsageOutput}%");
// 获取内存使用情况
string memoryUsageCommand = "free | grep Mem | awk '{print $3/$2 * 100.0}'";
string memoryUsageOutput = ExecuteShellCommand(memoryUsageCommand);
Console.WriteLine(#34;Memory Usage: {memoryUsageOutput}%");
// 获取磁盘使用情况
string diskUsageCommand = "df -h | awk '$NF==\"/\"{printf \"%s\", $5}'";
string diskUsageOutput = ExecuteShellCommand(diskUsageCommand);
Console.WriteLine(#34;Disk Usage: {diskUsageOutput}");
}
static string ExecuteShellCommand(string command)
{
string output = string.Empty;
try
{
ProcessStartInfo startInfo = new ProcessStartInfo
{
FileName = "/bin/bash",
Arguments = #34;-c \"{command}\"",
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
using (Process process = new Process())
{
process.StartInfo = startInfo;
process.Start();
output = process.StandardOutput.ReadToEnd();
process.WaitForExit();
}
}
catch (Exception ex)
{
Console.WriteLine(#34;Error executing shell command: {ex.Message}");
}
return output.Trim();
}
}
在上面的示例中,我们使用ExecuteShellCommand方法执行Shell命令并获取输出。
我们使用top命令获取CPU使用率,free命令获取内存使用情况,df命令获取磁盘使用情况。然后,我们将输出打印到控制台。
请注意,这些命令在Linux系统上运行,并且假设您的应用程序在Linux环境中运行。
确保您的应用程序具有执行Shell命令的权限。