linux内核态文件操作函数

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);

加载驱动之后现象为:

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值