Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2539955
  • 博文数量: 351
  • 博客积分: 76
  • 博客等级: 上将
  • 技术积分: 3555
  • 用 户 组: 普通用户
  • 注册时间: 2004-11-13 21:27
文章分类

全部博文(351)

文章存档

2013年(1)

2012年(4)

2011年(7)

2010年(16)

2009年(34)

2008年(34)

2007年(34)

2006年(68)

2005年(82)

2004年(71)

分类:

2005-09-29 10:44:15

在2.4.20的环境中重新写了The Linux Kernel Module Programming Guide中 6.1章节中的源代码,
源代码如下(没怎么写注释)。

/* ioproc.c - example code for i/o of proc file system
 *
 * Auth:    zhou weicheng
 * Date:    2005/9/28
 *
 * Usage:     You can op /proc/msg_file after insmod this module, use cat, echo or vi, etc.
 *                             echo "abc" > /proc/msg_file
 *                            cat /proc/msg_file                   
*/

#include linux/kernel.h
#include linux/module.h
#include linux/proc_fs.h
#include linux/version.h
#include asm/uaccess.h

#define MAX_MSG_LENGTH    256

static char *filename = "msg_file";
struct proc_dir_entry *msg_entry = NULL;
static char msg_stored[MAX_MSG_LENGTH];

MODULE_PARM(filename, "s");

static ssize_t output_msg(
     struct file *file,
        char *buf,
        size_t len,
        loff_t *offset)
{
    static int finished = 0;
    int i;

    if (finished) {
        finished = 0;
        return 0;
    }

    for (i = 0; i < len && msg_stored[i]; i++) {
        put_user(msg_stored[i], buf + i);
    }

    printk("output buf: %s ", buf);
    finished = i;
    return i;
}

static ssize_t input_msg(
     struct file *file,
        char *buf,
        size_t len,
        loff_t *offset)
{
    int i;
    for (i = 0; i < MAX_MSG_LENGTH && i < len; i++) {
        get_user(msg_stored[i], buf + i);
    }

    msg_stored[i] = '';
    printk("input: %s ", msg_stored);
    return i;
}

/*
 * only root can write the file
 * others can read
*/
static int check_perm(struct inode *i, int op)
{
    printk("Check Permition ");
    if ((op ==4) || ((op ==2) && (current->euid == 0))) {
        return 0;
    }
    return -EACCES;
}

int open_msg(struct inode *i, struct file *f)
{
    MOD_DEC_USE_COUNT;
   
    return 0;
}

int close_msg(struct inode *i, struct file *f)
{
    MOD_INC_USE_COUNT;
   
    return 0;
}

static struct file_operations msg_fops =
{
    read: output_msg,
    write: input_msg,
    open: open_msg,
    release: close_msg,
};

static struct inode_operations msg_iops =
{
    permission: check_perm
};

static int create_msg_file(void)
{
    msg_entry = create_proc_entry(filename, S_IFREG | S_IRUGO | S_IWUSR, &proc_root);
    if (!msg_entry) {
        return -ENOMEM;
    }

    msg_entry->proc_fops = &msg_fops;
    msg_entry->proc_iops = &msg_iops;

    return 0;
}

static int del_msg_file(void)
{
    remove_proc_entry(filename, &proc_root);
    return 0;
}

module_init(create_msg_file);
module_exit(del_msg_file);

阅读(2394) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~