📅  最后修改于: 2023-12-03 15:07:54.240000             🧑  作者: Mango
在Linux环境中,程序员需要获取系统和过程信息,以便进行调试和性能分析等应用场景。本文将介绍如何使用C编程和Shell脚本获取系统和过程信息。
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/sysinfo.h>
int main()
{
struct sysinfo info;
if (sysinfo(&info) == -1)
{
printf("Error: Failed to get system information.\n");
return -1;
}
printf("Total RAM: %lu MB\n", info.totalram / 1024 / 1024);
printf("Free RAM: %lu MB\n", info.freeram / 1024 / 1024);
printf("Used RAM: %lu MB\n", (info.totalram - info.freeram) / 1024 / 1024);
return 0;
}
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#define CPUINFO "/proc/cpuinfo"
int main()
{
char buf[512];
FILE *fp = fopen(CPUINFO, "r");
if (fp == NULL)
{
printf("Error: Failed to open file %s.\n", CPUINFO);
return -1;
}
while (fgets(buf, sizeof(buf), fp))
{
char *pos = strchr(buf, ':');
if (pos != NULL)
{
*pos = '\0';
printf("%s: %s\n", buf, pos + 2);
}
}
fclose(fp);
return 0;
}
#!/bin/bash
mem_info=$(free -m)
echo "Total RAM: $(echo "$mem_info" | awk 'NR==2{print $2}') MB"
echo "Free RAM: $(echo "$mem_info" | awk 'NR==2{print $4}') MB"
echo "Used RAM: $(echo "$mem_info" | awk 'NR==2{print $3}') MB"
#!/bin/bash
cpu_info=$(cat /proc/cpuinfo)
echo "$cpu_info" | while read line
do
pos=$(echo "$line" | grep -o ":" | wc -l)
if [ $pos -eq 1 ]
then
key=$(echo "$line" | awk -F ":" '{print $1}')
value=$(echo "$line" | awk -F ":" '{print $2}')
echo "$key: $value"
fi
done
本文介绍了在Linux环境中使用C编程和Shell脚本获取系统和过程信息的方法,包括获取内存信息和CPU信息。程序员可以根据自己的需求来选择使用哪种方式来获取信息,以便进行相关的应用场景。