13_char_devLinux内核模块


01_basicLinux内核模块_the kernel was built by:x86 64-linux-gnu-gcc-12(ub-CSDN博客文章浏览阅读638次,点赞3次,收藏3次。环境ID=ubuntuMakefilemodules:clean:basic.creturn 0;运行效果。_the kernel was built by:x86 64-linux-gnu-gcc-12(ubuntu 12.3.0-1ubuntu1~22.04https://blog.csdn.net/m0_37132481/article/details/136157384环境

root@T:/media/sf_D_DRIVE/kmodule/13_char_dev# cat /etc/os-release
PRETTY_NAME="Ubuntu 22.04.1 LTS"
NAME="Ubuntu"
VERSION_ID="22.04"
VERSION="22.04.1 LTS (Jammy Jellyfish)"
VERSION_CODENAME=jammy
ID=ubuntu
ID_LIKE=debian
HOME_URL="https://www.ubuntu.com/"
SUPPORT_URL="https://help.ubuntu.com/"
BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
UBUNTU_CODENAME=jammy
root@T:/media/sf_D_DRIVE/kmodule/13_char_dev#
 

my_char_dev.c

#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/cdev.h>

#define TAG "HELLO# "

#define COUNT 10
static dev_t my_devt;
static struct class *my_class;
static struct cdev *my_cdev;
struct device *my_device[COUNT];

static int my_cdev_open(struct inode *inode, struct file *file)
{
        printk(TAG "%s called\n", __func__);
        return 0;
}
static int my_cdev_release(struct inode *inode, struct file *file)
{
        printk(TAG "%s called\n", __func__);
        return 0;
}
static const struct file_operations my_cdev_fops = {
        .owner          = THIS_MODULE,
        .open           = my_cdev_open,
        .release        = my_cdev_release,
};

static int my_char_dev_init(void)
{
        int err;
        int i;
        printk(TAG "%s called\n", __func__);

        /* create /sys/class/my_class */
        my_class = class_create("my_class");
        my_cdev = cdev_alloc();

        cdev_init(my_cdev, &my_cdev_fops);

        err = alloc_chrdev_region(&my_devt, 0, COUNT, "dont'care");
        err = cdev_add(my_cdev, my_devt, COUNT);

        /* create /sys/dev/char/major:minor */
        for(i = 0; i < COUNT; i++)
        {
                my_device[i] = device_create(my_class, NULL, my_devt + i, NULL, "my_device_name%d", i);
        }

        return err;
}
static void my_char_dev_exit(void)
{
        int i;
        printk(TAG "%s called\n", __func__);

        for(i = 0; i < COUNT; i++)
        {
                device_destroy(my_class, my_devt + i);
        }

        unregister_chrdev_region(my_devt, COUNT);
        cdev_del(my_cdev);
        class_destroy(my_class);
}

module_init(my_char_dev_init);
module_exit(my_char_dev_exit);
MODULE_LICENSE("GPL");

效果

 

<完> 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值