/proc传结构体的方法

来源:互联网 发布:mac git冲突解决 编辑:程序博客网 时间:2024/06/03 23:50
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/proc_fs.h>
#include <linux/sched.h>
#include <linux/types.h>
#include <asm/uaccess.h>
#include <linux/slab.h> 
#include <linux/vmalloc.h>


#define STR_MAX_SIZE 255




typedef struct {
    int pid;
    int client_mod;
    struct list_head list;
} client_proc_t;


static struct proc_dir_entry * myprocroot;




client_proc_t client_proc;


static int struct_read_proc(char *page, char **start, off_t off,int count, int *eof, void *data)
{
    int count1;
    char buf[512];
    client_proc_t *tmp;
    struct list_head *pos; 
    struct list_head *q;
    
    count1 = 0;
    list_for_each_safe (pos, q, &(client_proc.list)) {
        tmp = list_entry(pos, client_proc_t, list);
        if (count1 >= 512) {
            printk("The buffer if full\n");
            break;
        }
        count1 += sprintf(&buf[count1], "%d-------%d\n",tmp->pid,tmp->client_mod);
       
    }
    memcpy(page,buf,count1);
           
    return count1;
}


int struct_write_proc(struct file *file, const char __user *buffer,
                           unsigned long count, void *data)
{
        int cli_pid;
        int mode;
        unsigned char file_name[STR_MAX_SIZE]; 
        client_proc_t *new;
        
        if (count > STR_MAX_SIZE) {
                 count = 255;
            }
        copy_from_user(file_name, buffer, count);
        //printk("%s\n",file_name);
        sscanf(file_name, "%d %d", &cli_pid, &mode);
        //printk("%d   %d\n",cli_pid,mode);
        new = (client_proc_t*)vmalloc(sizeof(client_proc_t));
        new->pid = cli_pid;
        new->client_mod = mode;
        list_add_tail(&(new->list), &(client_proc.list)); 


        return count;
}




static int __init procfs_exam_init(void)
{
    printk("is begging now \n");
#ifdef CONFIG_PROC_FS
        INIT_LIST_HEAD(&client_proc.list);
        struct proc_dir_entry * entry;
        myprocroot = proc_mkdir("myproctest", NULL);
        entry = create_proc_entry("astruct", 0666, myprocroot);
        if (entry) {
                entry->data = &client_proc;
                entry->read_proc = &struct_read_proc;
                entry->write_proc = &struct_write_proc; 
        }




#else
        printk("This module requires the kernel to support procfs,\n");
#endif




        return 0;
}


static void __exit procfs_exam_exit(void)
{
#ifdef CONFIG_PROC_FS
        remove_proc_entry("astruct", myprocroot);
        remove_proc_entry("myproctest", NULL);
        
#endif
client_proc_t *tmp;
    struct list_head *pos; 
    struct list_head *q;


    list_for_each_safe (pos, q, &(client_proc.list)) {
        tmp = list_entry(pos, client_proc_t, list);
        printk("%d-------%d\n",tmp->pid,tmp->client_mod);
        list_del(pos);
        vfree(tmp);
    }


}


module_init(procfs_exam_init);
module_exit(procfs_exam_exit);
MODULE_LICENSE("GPL");

0 0
原创粉丝点击