linux驱动开发之demo

来源:互联网 发布:网络暴力乔任梁粉红色 编辑:程序博客网 时间:2024/05/21 10:32

//LINUX 版本

#uname -r

2.6.18-1.2798.fc6
//编译 进入模块代码所在目录
$make -C /usr/src/kernels/2.6.18-1.2798.fc6 M=$(pwd) modules
//加载
#insmod test.ko
//查看主设备号(自动分配为No=253)
dmesg
//创建设备
mknod /dev/test c No 0
//修改权限
chmod 666 /dev/test
//写入字符
echo -n abcdef >/dev/test
//检查内容(该程序还有些问题,读不停止....ctrl+c)
cat /dev/test

//卸载模块
rmmod test

rm -rf /dev/test

源代码:

test.c

#include <linux/module.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <asm/uaccess.h>
#include <linux/errno.h>

unsigned int fs_major = 0;
static char *data;

static ssize_t test_read(struct file *file, char *buf, size_t count, loff_t *fpos);
static ssize_t test_write(struct file *file, const char *buffer, size_t count, loff_t *f_pos);
static int test_open(struct inode *inode, struct file *file);
static int test_release(struct inode *inode, struct file *file);
int test_init(void);
void test_exit(void);
static struct file_operations chr_fops={
        read: test_read,
        write: test_write,
        open: test_open,
        release: test_release
};


static ssize_t test_read(struct file *file, char *buf, size_t count, loff_t *f_pos)
{
    int len;
    if(count<0)
        return -EINVAL;
    len = strlen(data);
    printk("<1>\nread--Count:%d,allLen:%d\n",count,len);
    #if 0
    if(len<count)
        count = len;
    copy_to_user(buf,data, count+1);
    #else
    //if(len<count)
    //    count = len;
    copy_to_user(buf,data, len+1);
    #endif
    return count;
}

static ssize_t test_write(struct file *file, const char *buffer, size_t count, loff_t *f_pos)
{
    if(count<0)
        return -EINVAL;
    kfree(data);
    data = (char *)kmalloc(sizeof(char)*(count+1), GFP_KERNEL);
    copy_from_user(data, buffer,count+1);
    return count;
}

static int test_open(struct inode *inode, struct file *file)
{
    //MOD_INC_USE_COUNT;
    printk("<1>This is Open\n");
    return 0;
}

static int test_release(struct inode *inode, struct file *file)
{
    //MOD_DE_USE_COUNT;
    printk("<1>This is Released\n");
    return 0;
}

int test_init(void)
{
    int res;
    res = register_chrdev(0,"fs", &chr_fops);
    if(res<0)
    {
        printk("<1> Cann't get major number!\n");
        return res;
    }
    if(fs_major==0)
    {
        fs_major = res;
        printk("<1>Allocal Major:%d\n",fs_major);
    }
    return 0;
}

void test_exit(void)
{
    unregister_chrdev(fs_major, "fs");
}

module_init(test_init);
module_exit(test_exit);

Makefile:

obj-m:=test.o

原创粉丝点击