1.打开文件
struct file *filp_open(const char *filename, int flags, int mode)
filename:要打开的文件的路径 例:“/dev/ttyGS0”
flags:打开文件的方式
O_CREAT 创建
O_RDWR 读写
O_RDONLY 只读
O_WRONLY 只写
O_TRUNC 清空
O_EXCL 一般会与O_CREAT一起使用 O_CREAT|O_EXCL表示如果存在指定文件 则报错 不存在则创建
mode:可有可无 如果flags为O_CREAT 这个参数才有效 此时 这个参数表示要创建的文件的访问权限
例:权限为0755 rwxr xr x
第一组(rwx):表示文件所有者的权限,该文件的所有者为root,具备可读
可写
可执行
的全部权限
第二组(r-x):文件所属组的权限,具备可读
可执行
第三组(r-x):其他人的权限(跟本文件无关的人),具备可读
可执行
2.close
int filp_close(struct file *filp, fl_owner_t id)
其中filp为open时函数返回的值
3、read
ssize_t vfs_read(struct file *file, char __user *buf, size_t count, loff_t *pos)
file:open函数返回的文件描述符
buf:读取的数据存放的缓冲区
count:想要读取的字节数
pos:文件的偏移地址
4.write
ssize_t vfs_write(struct file *file, const char __user *buf, size_t count, loff_t *pos)
file:open函数返回的文件描述符
buf:写入的数据缓冲区
count:想要写入的字节数
pos:文件的偏移地址
内核空间使用vfs_read和vfs_write函数需要涉及函数set_fs和get_fs,具体讲解在https://mp.csdn.net/postedit/85082643中
例:
#include <linux/dcache.h>
#include <linux/fs.h>
#include <asm/processor.h>
#include <asm/uaccess.h>
#include <linux/init.h>
#include <linux/err.h>
#include <linux/string.h>
#include <linux/errno.h>
#include <asm/fcntl.h>
#include <linux/module.h>
#include <linux/sched.h>
int __init zt_init(void)
{
unsigned char buffer1[12]="kernel zhang";
unsigned char buffer2[12]="kernel tao54";
unsigned char buffer_read[24];
mm_segment_t fs;
struct file *fp;
loff_t pos;
loff_t pos_buf;
int i = 0;
fp = filp_open("/home/zhangtao/share/globalmem/file", O_RDWR | O_CREAT, 0666);
if (IS_ERR(fp)) {
printk("create file error\n");
return -1;
}
fs = get_fs();
set_fs(KERNEL_DS);
pos = fp->f_pos;
pos_buf = pos;
printk("%s %d %d\n",__func__,__LINE__,pos_buf);
vfs_write(fp, buffer1, sizeof(buffer1), &pos);
fp->f_pos = pos;
pos = fp->f_pos;
vfs_write(fp, buffer2, sizeof(buffer2), &pos);
fp->f_pos = pos;
vfs_read(fp, buffer_read, 24, &pos_buf);
for(i = 0; i < 24; i++)
printk("%c",buffer_read[i]);
printk("\n");
set_fs(fs);
filp_close(fp, NULL);
return 0;
}
void __exit zt_exit(void)
{
printk("taozhang54 exit\n");
}
module_init(zt_init);
module_exit(zt_exit);
加载驱动之后现象为: