基于内核的简单文件读写
/*
gcc -c fileread.c -O2 -DMODULE -D_KERNEL_ -o fileread.o
Redhat7.2 compiled successfully
*/
#define MODULE
#define __KERNEL__
#include
#include
#include
#include
#include
MODULE_AUTHOR("IDS.");
MODULE_DESCRIPTION("Kernel study and test.");
void fileread(const char * filename)
{
struct file *filp;
struct inode *inode;
mm_segment_t fs;
off_t fsize;
char *buf;
int i;
unsigned long magic;
printk("<1>start....\n");
filp=filp_open(filename,O_RDONLY,0);
inode=filp->f_dentry->d_inode;
/* inode->i_ino=291588; */
/* file system magic number */
magic=inode->i_sb->s_magic;
printk("<1>file system magic:%li \n",magic);
printk("<1>super blocksize:%li \n",inode->i_sb->s_blocksize);
printk("<1>inode %li \n",inode->i_ino);
fsize=inode->i_size;
printk("<1>file size:%i \n",fsize);
buf=(char *) kmalloc(fsize+1,GFP_ATOMIC);
fs=get_fs();
set_fs(KERNEL_DS);
filp->f_op->read(filp,buf,fsize,&(filp->f_pos));
set_fs(fs);
buf[fsize]='\0';
printk("<1>The File Content is:\n");
printk("<1>%s",buf);
filp_close(filp,NULL);
}
int init_module()
{
char *filename="/root/test";
printk("<1>Read File from Kernel.\n");
fileread(filename);
return 0;
}
void cleanup_module()
{
printk("<1>Good,Bye!\n");
}
阅读(1044) | 评论(0) | 转发(0) |