Proc File
Proc FS 被称为进程文件系统,在/proc文件夹下,存储了各个进程的详细的信息。与此同时proc也作为一种应用层和内核交互的手段。
Proc function
proc FS除了存储各个进程的详细信息,也会在proc的虚拟文件系统中存储内核的状态数据,用于调试。
Proc usage
从使用的角度,通常情况下proc下的文件都是可读的,即我们通过proc读取内核的一些状态信息,读取方法: cat /proc/cpuinfo.
也不排除部分proc文件是可写的,即从用户态写一些配置信息到proc文件中,从而改变内核的运行。配置方法: echo /proc/xxx
Note: proc fs的初衷是进程文件系统,所以proc文件夹放置的跟进程无关的信息正在逐步移植到sys文件系统中。
常见的proc信息
- cat /proc/info
- cat /proc/meminfo
- cat /proc/mounts
- cat /proc/cmdline
- cat /proc/devices
- cat /proc/filesystems
- cat /proc/modules
- cat /proc/partitions
Design one Proc File.
Note: 此处的用法是基于Linux4.1 版本,随着版本变化,用法也会有所区别。
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/uaccess.h>
#include <linux/proc_fs.h>
#include <linux/fs.h>
#include <linux/seq_file.h>
#include <linux/slab.h>
struct proc_dir_entry *proc_dir;
static char * str = NULL;
static int my_proc_show(struct seq_file *m, void * v)
{
seq_printf(m,"current kernel time is %ld\n", jiffies);
seq_printf(m,"str is %s\n", str);
return 0;
}
static int my_proc_open(struct inode * inode, struct file *file)
{
return single_open(file, my_proc_show, NULL);
}
static struct file_operations my_fops =
{
.owner = THIS_MODULE,
.open = my_proc_open,
.release = single_release,
.read = seq_read,
.llseek = seq_lseek,
};
static int __init my_init(void)
{
struct proc_dri_entry *file;
proc_dir = proc_mkdir("myproc", NULL);
if (!proc_dir)
{
return -ENOMEM;
}
file = proc_create("abc_proc", 0644, proc_dir, &my_fops);
if (!file)
return -ENOMEM;
return 0;
}
static void __exit my_exit(void)
{
remove_proc_entry("abc_proc", proc_dir);
remove_proc_entry("myproc", NULL);
kfree(str);
}
module_init(my_init);
module_exit(my_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Johnson");
Makefile
obj-m :=proc_test.o
KERNEL := /lib/modules/`uname -r`/build
all:
make -C $(KERNEL) M=`pwd` modules
install:
make -C $(KERNEL) M=`pwd` modules_install