在Linux应用态,我们可以调用Linux系统调用轻松的读写文件,但是在Linux内核中,不能直接调用READ/WRITE系统调用来进行读写。
下面是Linux内核中读写文件/设备的一种方法:
struct file *filp;
mm_segment_t oldfs;
//打开文件,不同的文件系统或者设备
filp = filp_open("/db_name", O_RDWR|O_CREAT|O_APPEND, 0640);
if (!filp || IS_ERR(filp))
printk("open file /db_name error"));
else
if (filp->f_op->write)
{
//相当于lseek到文件头部
filp->f_pos = 0;
oldfs = get_fs();
set_fs(KERNEL_DS);
//不同的文件系统或者设备,f_op不同
bytes = filp->f_op->write(filp, buf, len, &filp->f_pos);
set_fs(oldfs);
/* close the file */
fput(filp);
}
else
printk("filp->f_op->write is null");
|