Objective
Welcome everyone I share and recommend useful code Snippets ~ ~
Statement
Welcome reprint, but please keep the original source of the article:
Csdn:http://www.csdn.net
Rainy season o mo away: http://blog.csdn.net/luckkof
Body
[Description]
How to read and write files in Linux kernel
[Keyword]
Linux kernel read Write file read-write files
[Solution]
Usually we just read and write files on the Linux Native/app layer, but there may be some very special cases where we need to read and write file information directly in the kernel.
The following is a typical code:
static struct file *open_file (char *path,int flag,int mode)
{
struct file *fp;
Fp=filp_open (path, flag, mode);
if (!is_err_or_null (FP)) return FP;else return NULL;
}static int read_file (struct file *fp,char *buf,int readlen)
{
if (fp->f_op && fp->f_op->read)
Return Fp->f_op->read (Fp,buf,readlen, &fp->f_pos);
Else
return-1;
}static int write_file (struct file *fp,char *buf,int len)
{
if (fp->f_op && fp->f_op->write)
Return Fp->f_op->write (FP, buf, Len, &fp->f_pos);
Else
return-1;
}static int close_file (struct file *fp)
{Filp_close (fp,null);
return 0;}Note that you need to use Read_file & Write_file before
Read set kernel domain
Set_fs (Kernel_ds);
After Read_file & Write_file is complete, you need to
Need set user domain again
Set_fs (User_ds);
Must become the right to appear, otherwise it will directly lead to kernel Crash.last but not least: assume that you can read and write files on the Linux Native/app layer, and try not to do this in kernel. Due to this potential security issue, and the possible impact of kernel stability due to new code