三、创建proc文件
实例:
proc.c
-
#include <linux/module.h>
-
#include <linux/proc_fs.h>
-
#include <linux/seq_file.h>
-
#include <linux/kernel.h>
-
#include <linux/slab.h>
-
#include <linux/uaccess.h>
-
-
static int hello_proc_show(struct seq_file *m, void *v) {
-
seq_printf(m, "hello proc!\n");
-
return 0;
-
}
-
static int hello_proc_open(struct inode *inode, struct file *file) {
-
return single_open(file, hello_proc_show, NULL);
-
}
-
-
static ssize_t hello_proc_write(struct file *file, const char __user *buffer, size_t count, loff_t *f_pos)
-
{
-
char *tmp = kzalloc(sizeof(char)*count, GFP_KERNEL);
-
if (!tmp)
-
return -ENOMEM;
-
-
if (copy_from_user(tmp, buffer, count)) {
-
kfree(tmp);
-
return -EFAULT;
-
}
-
*f_pos += count;
-
-
printk(KERN_ALERT "hello_proc_write %s\n", tmp);
-
-
kfree(tmp);
-
return count;
-
}
-
-
static ssize_t hello_proc_read(struct file *file, const char __user *buffer, size_t count, loff_t *f_pos)
-
{
-
char *tmp = kzalloc(sizeof(char)*count, GFP_KERNEL);
-
if (!tmp)
-
return -ENOMEM;
-
-
snprintf(tmp, sizeof(char)*count, "hello proc file!");
-
printk(KERN_ALERT "hello_proc_read %s\n", tmp);
-
-
if (copy_to_user((char*)buffer, tmp, count)) {
-
kfree(tmp);
-
return -EFAULT;
-
}
-
*f_pos += count;
-
-
kfree(tmp);
-
return count;
-
}
-
-
static const struct file_operations hello_proc_fops = {
-
.owner = THIS_MODULE,
-
.open = hello_proc_open,
-
.read = hello_proc_read,
-
.llseek = seq_lseek,
-
.release = single_release,
-
.write = hello_proc_write,
-
};
-
static int __init hello_proc_init(void) {
-
struct proc_dir_entry *hello_proc_dir = proc_mkdir("hello", NULL);
-
if (NULL == hello_proc_dir) {
-
return -EFAULT;
-
}
-
if (!proc_create("hello_proc", 0644, hello_proc_dir, &hello_proc_fops)) {//从Linux 内核V3.10版本开始,内核源码不再提供create_proc_read_entry及create_proc_entry两个函数的支持,已经被proc_create()函数取代。
-
return -EFAULT;
-
}
-
printk(KERN_ALERT "hello_proc_init\n");
-
return 0;
-
}
-
-
static void __exit hello_proc_exit(void) {
-
remove_proc_entry("hello_proc", NULL);
-
printk(KERN_ALERT "hello_proc_exit\n");
-
}
-
-
MODULE_LICENSE("GPL");
-
-
module_init(hello_proc_init);
-
module_exit(hello_proc_exit);
proc_makefile
-
obj-m := proc.o
-
-
KERNEL := /lib/modules/`uname -r`/build
-
-
all:
-
make -C $(KERNEL) M=`pwd` modules
-
install:
-
make -C $(KERNEL) M=`pwd` modules_install
-
depmod -A
-
clean:
-
make -C $(KERNEL) M=`pwd` clean
参考:proc_mkdir与proc_create 使用proc_create创建proc文件
四、用户态读写proc
实例:
-
#include <stdio.h>
-
#include <string.h>
-
-
int main()
-
{
-
char buff[32] = {0};
-
FILE *fp = NULL;
-
-
fp = fopen("/proc/hello/hello_proc", "r+");
-
if(fp == NULL)
-
{
-
perror("fopen()");
-
return -1;
-
}
-
-
if(fread(buff, sizeof(char), 1, fp) != 1)
-
{
-
perror("fread()");
-
fclose(fp);
-
return -2;
-
}
-
-
printf("%s\n", buff);
-
-
fclose(fp);
-
-
return 0;
-
}
阅读(4651) | 评论(0) | 转发(0) |