kernel中对文件的读写【学习笔记】【原创】

/*1. 头文件 */
#include <linux/init.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/kernel.h>
#include <linux/list.h>
#include <linux/fs.h>
#include <linux/uaccess.h>

MODULE_PARM_DESC(ivar, "module kernel list");



static char buf[] = "aa:aa:aa:aa:aa:aa";
static char readbuf[128];
/* 2.模块的加载函数*/
static int __init hello_init(void)
{
    struct file *fp;
    mm_segment_t fs;
    loff_t pos;


    fp = filp_open("/sys/kernel/pax_ethernet/mac",O_RDWR|O_CREAT,0644);
    if(IS_ERR(fp)){
        printk("create file error
");
        return -1;
    }

    fs = get_fs();
    set_fs(KERNEL_DS);
    pos = 0;
    vfs_write(fp,buf,sizeof(buf),&pos);
    pos = 0;
    vfs_read(fp,readbuf,sizeof(readbuf),&pos);
    printk("Read:%s
",readbuf);
    filp_close(fp,NULL);
    set_fs(fs);
    


    return 0;
}

/* 3.模块的卸载函数*/
static void __exit hello_exit(void)
{
  printk("Bye, drivers!
");    
}

/*4. 模块的入口和出口*/
module_init(hello_init);
module_exit(hello_exit);

/*5.模块的许可声明*/
MODULE_LICENSE("GPL");

Makefile

ifeq ($(KERNELRELEASE),)
KERNELDIR ?=/home/zhuangzb/project/rk3288-e810-android6.0/kernel #内核路径
PWD :=$(shell pwd)   #当前路径

modules:
    $(MAKE) -C $(KERNELDIR) M=$(PWD) modules
    #cp hello.ko /opt/fs210/filesystem/drivers/ -f
modules_install:
    $(MAKE) -C $(KERNELDIR) M=$(PWD) modules_install
clean:
    rm -rf *.o *~core *.ko *.mod.c .tmp_versions Module.symvers modules.order
else
        obj-m :=kernel_file.o        #生成hello.ko
原文地址:https://www.cnblogs.com/zzb-Dream-90Time/p/8253714.html