如何在linux内核中读写文件

如何在linux内核中读写文件,第1张

首先保证系统有linux内核源码 下载内核源码,版本可以更改 1>sudo apt-get install linux-source-2.6.35 下载内核源码一般在/usr/src目录中 2>进入/usr/src中解压内核源码 3>然后执行cd /usr/src/内核目录

内核模块linux源代码联系些概念我都模糊linux系统由各种各内核模块组

实验源代码:

//my_proc.c

#include<linux/module.h>

#include<linux/kernel.h>

#include<linux/proc_fs.h>

#include<linux/sched.h>

#include<linux.uaccess.h>

#define STRINGLEN 1024

char global_buffer[STRINGLEN]

struct proc_dir_entry *example_dir,*Tang_file,*Yang_file,*symlink

int proc_read_Tang(char *page,char **start,off_t off,int count,int *eof,void *data)

{//用户读取Tang文件内核调用函数

int len

try_module_get(THIS_MODULE)//模块引用计数器

len=printf(page,"Tang message:\nname: %s\npid: %d\n",current->comm,current->pid)

module_put(THISMODULE)

return len

}

int proc_read_Yang(char *page,char **start,off_t off,int count,int *eof,void *data)

{//用户读取Yu文件内核调用函数

int len

try_module_get(THIS_MODULE)

len=printf(page,"Yang message:\n%s write: %s\n",current->comm,global_buffer)

module_put(THISMODULE)

return len

}

int proc_write_Yang(struct file *file, const char *buffer, unsigned long count, void *data)

{//用户读写数据入Yang文件内核调用函数

int len

try_module_get(THIS_MODULE)

if(count>=STRINGLEN)

len=STRINGLEN-1

else

len=count

copy_from_user(global_buffer,buffer,len)

global_buffer[len]='\0'

module_put(THISMODULE)

return len

}

int init_module()

{//初始化函数

example_dir=proc_mkdir("13081175",NULL)

example_dir->owner=THIS_MODULE

Tang_file=create_proc_read_entry("Tang",0444,example_dir,proc_rea d_current,NULL)

Tang_file->read_proc=proc_read_Tang

Tang_file->owner=THIS_MODULE

Yang_file=create_proc_entry("Yang",0666,example)

strcpy(global_buffer,"Tang")

Yang_file->read_proc=proc_read_Yang

Yang_file->write_proc=proc_write_Yang

Yang_file->owner=THIS_MOUDLE

return 0

}

void cleanup_module()

{//卸载函数

remove_proc_entry("Yang",example_dir)

remove_proc_entry("Tang",example_dir)

remove_proc_entry("21",NULL)

}

编写Makefile文件内容:

obj-m := my_proc.o

KERNELBUILD :=/lib/modules/$(shell uname -r)/build

default:

make -C $(KERNELBUILD) M=$(shell pwd) modules

clean:

rm -rf *.o *.ko *.mod.c .*.cmd *.markers *.order *.symvers .tmp_versions


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/yw/8384088.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-04-15
下一篇2023-04-15

发表评论

登录后才能评论

评论列表(0条)

    保存