48_proc文件系统的使用

本文提供了一个通过C程序读取Linux proc文件系统中version、cpuinfo和devices信息的例子,并对比了proc与sys文件系统的特点。展示了如何利用C语言标准库函数实现文件读取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

proc文件系统的使用,一般有两种方法

一种是手工cat查看,上节课介绍过啦

另一种在程序中查看,以文件IO访问

也可以在shell中再用正则表达式处理

#include<stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>


int main(int argc, char **argv)
{
	int fd;
	char buf[512];
	
	if(argc != 2)
	{
		printf("usage : %s version | cpuinfo | devices \n", argv[0]);
		return -1;
	}
	
	if(!strcmp(argv[1], "version"))
	{
		fd = open("/proc/version", O_RDONLY);
		if(fd < 0)
		{
			perror("open");
			return -1;		
		}
		
		memset(buf, 0, sizeof(buf));
		read(fd, buf, sizeof(buf));
		printf("buf: %s.", buf);
	}
	else if(!strcmp(argv[1], "devices"))
	{
		fd = open("/proc/devices", O_RDONLY);
		if(fd < 0)
		{
			perror("open");
			return -1;		
		}
		
		memset(buf, 0, sizeof(buf));
		read(fd, buf, sizeof(buf));
		printf("buf: %s.", buf);
	}
	else if(!strcmp(argv[1], "cpuinfo"))
	{
		fd = open("/proc/cpuinfo", O_RDONLY);
		if(fd < 0)
		{
			perror("open");
			return -1;		
		}
		
		memset(buf, 0, sizeof(buf));
		read(fd, buf, sizeof(buf));
		printf("buf: %s.", buf);
	}
	
	return 0;	
}

sys文件系统的特点


按理说应该是一个,这是历史原因造成的,现有proc后又sys

有了proc发现很好,后来开发者就都去proc添加文件,结果众多开发者都向proc添加,管理者一开始也没有经验,后来的结果就是proc的内容又多又杂乱,这是一个摸索的过程,后来于是乎就重启炉灶,在sys规划好顶层设计,proc依然保留,这是为了向前兼容,sys优势就是 做了很好的规划。很有规律,对于使用者就是福音,进去一看文件存放确实很规范,编写驱动就操作这里







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值