如何通过C w / o使用bash脚本添加char设备

时间:2012-03-12 04:24:06

标签: c linux module kernel driver

我想通过C代码在我的Linux目录中向/devices添加一个char设备。由于我创建了仅在我insmod my_module.ko时存在的虚构驱动程序,我希望我的模块为我创建一个设备。下面是我的代码中应该添加设备的部分,但我只是初始化我的cdev struct并告诉内核它。

int start_mod(void){
    //Because we are dealing with a fictitious device, I want
    //the driver to create my two devices with arbitrarly 
    //assigned major numbers.

    alloc_chrdev_region(&dev_num, FIRST_MINOR, COUNT, DEVICE_NAME); // This assigns my device name
                                    // as well as asign Major # my driver uses

    cdev_init(&(my_dev->my_cdev), &fops);// This initializes my cdev struct that the kernel uses to keep track of my device
    my_dev->my_cdev.owner = THIS_MODULE;
    my_dev->my_cdev.ops = &fops;// fops is my file operations struct

    int err = cdev_add(&(my_dev->my_cdev), dev_num, COUNT);// this in theory should give a pointer to the kernel
    // to my cdev struct that I have setup to exist in my other structure.

    // Now I need to officially add my device to /devices folder.
    return 0;   
}

我不确定要将char设备正式添加到内核需要做什么。

2 个答案:

答案 0 :(得分:2)

过去曾使用mknod()系统调用...但只有root - 特权进程才能在/dev中创建设备。

答案 1 :(得分:2)

您所做的是使用内核中的一些较新的注册函数,如class_createdevice_create。这将允许udev创建您的设备。

你是说你在没有看任何其他司机的情况下写了一个司机? 因为有关如何注册字符设备的例子并不缺乏。

查看

drivers/char

顺便提一下,前面提到的那些函数只是GPL,如果你想重新发布代码就会产生影响。