A simple charactor device driver code using sysfs and udev

 

/* test.c
 * use "insmod test.ko"
 * can see "/dev/test"
 * and "test" in "/proc/devices"
 */


#include <linux/init.h>
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/types.h>    /* dev_t */
#include <linux/cdev.h>        /* struct cdev */
#include <linux/device.h>    /* device_create() */
#include <linux/fs.h>        /* struct file_operations */


#define DEVICE_NAME "test"

static struct cdev test_dev;
static struct class *test_class;
static dev_t test_devno;

static int test_open(struct inode *inode, struct file *filp)
{
    printk(KERN_ALERT "The process is \"%s\" (pid %i)\n",
        current->comm, current->pid);
    return 0;
}


static struct file_operations test_fops = 
{
    .owner = THIS_MODULE,
    .open = test_open,
};

static int __init test_init(void)
{
    int ret;
    unsigned int first_minor = 0;
    unsigned int count = 1;
    /* get dev_t from kernel */
    ret = alloc_chrdev_region(&test_devno,first_minor,count,DEVICE_NAME);
    if(ret < 0) return ret;

/* init cdev and fops */ cdev_init(&test_dev,&test_fops); test_dev.owner = THIS_MODULE;/* add the dev_t to cdev */ cdev_add(&test_dev, test_devno,count); /* create a class named as DEVICE_NAME, show as /sys/class/DEVICE_NAME */ test_class = class_create(THIS_MODULE, DEVICE_NAME); if(IS_ERR(test_class)) { printk(KERN_ALERT "create test_class error."); return -1; } /* create device by /sys/class/DEVICE_NAME and the dev_t, show as /dev/DEVICE_NAME */ device_create(test_class,NULL,test_devno,NULL,DEVICE_NAME); printk(KERN_ALERT DEVICE_NAME " initialized\n"); return 0; } static void __exit test_exit(void) { unsigned int count = 1; cdev_del(&test_dev); unregister_chrdev_region(test_devno,count); device_destroy(test_class,test_devno); class_destroy(test_class); printk(KERN_ALERT DEVICE_NAME " released\n"); } module_init(test_init); module_exit(test_exit); MODULE_LICENSE("GPL");

 

#Makefile

OBJ=test

ifneq ($(KERNELRELEASE),)
    obj-m := ${OBJ}.o
    module-objs := ${OBJ}.o

else

    KERNELDIR := /lib/modules/$(shell uname -r)/build
    PWD := $(shell pwd)
defualt:
    $(MAKE) -C $(KERNELDIR) M=$(PWD) modules

endif


clean:
    rm *.o *.ko *.mod.c

 

转载于:https://www.cnblogs.com/kozmers/p/4465446.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值