在内核中访问 文件系统里的文件
时间:2010-10-19 来源:BENNYSNAKE
#include <linux/version.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/fcntl.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/firmware.h>
#include <linux/fs.h>
#include <asm/uaccess.h>
#include <linux/mempolicy.h>
#include <linux/mount.h>
MODULE_LICENSE("GPL");
/**
** \fn openFile
** \brief Open a file
** \param pathname the path to the file to be opened
*\param flags permision flags to open the file with
* * \param mode mode flags to open the file with
* * \param uid owner user id
* * \param gid owner group id
* * \return file_ptr pointer to the opened file
* * NULL - err_code error opening as indicated by the error code
* */
static struct file *openFile (const char *filename, int32_t flags, int32_t mode, uid_t uid, gid_t gid)
{
struct file *file;
do {
struct dentry *saved_root = current->fs->pwd.dentry;
struct vfsmount *saved_mnt = current->fs->pwd.mnt;
current->fs->pwd.dentry = init_task.fs->pwd.dentry;
current->fs->pwd.mnt = init_task.fs->pwd.mnt;
if (NULL == (file = filp_open (filename, flags, mode)))
printk(KERN_ERR "kermit: can't open file %s!\n", filename);
current->fs->pwd.mnt = saved_mnt;
current->fs->pwd.dentry = saved_root;
} while (0);
return file;
}
/**
* * \fn closeFile
* * \brief Close a file
* * \param file pointer to the file to be closed
* * \return 0 success
* * != 0 error closing the file as indicated by the error code
* */
static int32_t closeFile (struct file *file)
{
return filp_close (file, current->files);
}
/**
* * \fn readFile
* * \brief Read from a file
* * \param file pointer to the file to be read from
* * \param addr buffer to hold the read data
* * \param len number of bytes to read
* * \param pos starting position
* * \return number of bytes read
* *
* * \warning file should be a valid file pointer
* * and the corresponding file should
* * be opened, i.e. the file should
* * located be on the linked node
* */
static int32_t readFile(struct file *file, char *addr, size_t len, loff_t *pos)
{
int32_t ret;
do {
mm_segment_t old_fs;
old_fs = get_fs();
set_fs(KERNEL_DS); /* Enable to read in kernel memory */
ret = vfs_read(file, addr, len, pos);
set_fs(old_fs); /* Disable to read in kernel memory */
} while (0);
return ret;
}
static int __init hello_init (void)
{
char cbuf[128] = {0};
printk("Hello module init\n");
struct file *lut_fp = openFile("/tmp/1.txt", 0, 0, 0, 0);
if (NULL == lut_fp ) {
return 0;
}
lut_fp->f_pos = 0;
readFile(lut_fp, cbuf, sizeof(cbuf), &lut_fp->f_pos);
printk("%s \n", cbuf);
closeFile (lut_fp);
return 0;
}
static void __exit hello_exit (void)
{
printk("Hello module exit\n");
}
module_init(hello_init);
module_exit(hello_exit);