procfs小测试

来源:互联网 发布:网络上卖大米挣钱吗? 编辑:程序博客网 时间:2024/06/03 23:47
/** *  procfs.c -  create a "file" in /proc * */#include <linux/module.h>   /* Specifically, a module */#include <linux/kernel.h>   /* We're doing kernel work */#include <linux/proc_fs.h>  /* Necessary because we use the proc fs */#include <asm/uaccess.h>    /* for copy_from_user */#include <linux/fs.h>#include <linux/seq_file.h>#include <linux/init.h>#define PROCFS_MAX_SIZE     1024#define PROCFS_NAME         "procfstest"/** * This structure hold information about the /proc file * */static struct proc_dir_entry *Our_Proc_File = NULL;/** * The buffer used to store character for this module * */static char procfs_buffer[PROCFS_MAX_SIZE];/** * The size of the buffer * */static unsigned long procfs_buffer_size = 0;static int procfile_show(struct seq_file *m, void *v){    seq_printf(m, "%s", procfs_buffer);    return 0;}static int procfile_open(struct inode *inode, struct file *file){    return single_open(file, procfile_show, NULL);}/** * This function is called with the /proc file is written * */static ssize_t procfile_write(struct file *file, const char __user *buffer, size_t count, loff_t *f_ops){    // size must less than the buffer size    procfs_buffer_size = count > PROCFS_MAX_SIZE? PROCFS_MAX_SIZE-1 : count;    /* write data to the buffer */    if ( copy_from_user(procfs_buffer, buffer, procfs_buffer_size) ) {        return -EFAULT;    }    procfs_buffer[procfs_buffer_size] = '\0';    return procfs_buffer_size;}static const struct file_operations procfile_fops = {    .open = procfile_open,    .read = seq_read,    .write = procfile_write,    .llseek = seq_lseek,    .release = single_release,};/** *This function is called when the module is loaded * */int procfile_init(void){    /* create the /proc file */    if(!Our_Proc_File)    {        Our_Proc_File = proc_create(PROCFS_NAME, 0777, NULL, &procfile_fops);        if(!Our_Proc_File)        {            printk(KERN_ERR "create %s err!!\n", "/proc/"PROCFS_NAME);            return 1;        }    }    printk(KERN_INFO "create %s success!!\n", "/proc/"PROCFS_NAME);    return 0;   /* everything is ok */}/** *This function is called when the module is unloaded * */void procfile_exit(void){    if(Our_Proc_File)    {        remove_proc_entry(PROCFS_NAME, Our_Proc_File);        //proc_remove(Our_Proc_File);    }    printk(KERN_INFO "/proc/%s removed\n", PROCFS_NAME);}module_init(procfile_init);module_exit(procfile_exit);MODULE_LICENSE("GPL");
0 0
原创粉丝点击