llseek方法实现了lseek和llseek系统调用,如果设备操作未定义llseek方法,内核默认通过修改filp->f_pos执行定位,filp->f_pos是文件的当前读写位置。为了使lseek系统调用正常工作,read和write方法需要更新它们收到的偏移量参数。
然而大多数设备定位是没有意义的,这些设备只提供数据流,而不是数据区。如果不需要llseek方法,不能简单地不声明llseek,因为默认是允许定位的。应该在open方法中调用nonseekable_open通知内核设备不支持llseek,filp将被标记为不可定位;为了完整,还应该将file_operations中的llseek设置为no_llseek(定义在<linux/fs.h>)。
int nonseekable_open(struct inode *inode, struct file *filp);
#include <linux/init.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/kdev_t.h>
#include <linux/fs.h>
#include <linux/cdev.h>
#include <linux/uaccess.h>
#define MAX_BUF_LEN 1024
static int major = 277;
static int minor = 0;
static dev_t helloNum;
struct class *helloClass = NULL;
struct device *helloDev = NULL;
static char helloBuf[MAX_BUF_LEN] = {0};
static loff_t hell

本文介绍了Linux内核中llseek方法的作用,它用于实现文件的定位操作。当设备不支持定位时,需要在open方法中调用nonseekable_open来禁止,并将file_operations中的llseek设置为no_llseek。示例代码展示了如何自定义字符设备驱动的llseek方法以支持SEEK_SET、SEEK_CUR和SEEK_END操作。同时,给出了用户空间的示例程序来演示读写及定位操作。
最低0.47元/天 解锁文章
1

被折叠的 条评论
为什么被折叠?



