Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I call mknod from my kernel module?

As the title states I'm writing a kernel module and I want the character device that the module creates to show up automatically. can I use mknod and rm in my module_init and module_exit to create and remove the device?

EDIT: not sure if this is allowed but as an extension to the question, where can I find more information like this? most of my google searches lead to either very confusing for very old information (kernel 2.6 and older), whats the best place to learn how to write kernel modules?

like image 770
zee Avatar asked Sep 06 '25 03:09

zee


1 Answers

No you can't use mknod and rm cli's from kernel space. These are bash commands. But other option exists to create and remove the device node file of your module from kernel space. In module init function you can use class_create() and then device_create() functions after doing registration for you device. After cdev_init() call you can use this two function for node file creation. Similarly you can use device_destroy() and class_destroy() functions in module_exit function to remove the node file.

Here is sample code that creates /dev/kmem in a char device init function:

int majorNum;
dev_t devNo;  // Major and Minor device numbers combined into 32 bits
struct class *pClass;  // class_create will set this

static int __init devkoInit(void) {
  struct device *pDev;

  // Register character device
  majorNum = register_chrdev(0, "devko", &fileOps);
  if (majorNum < 0) {
    printk(KERN_ALERT "Could not register device: %d\n", majorNum);
    return majorNum;
  }
  devNo = MKDEV(majorNum, 0);  // Create a dev_t, 32 bit version of numbers

  // Create /sys/class/kmem in preparation of creating /dev/kmem
  pClass = class_create(THIS_MODULE, "kmem");
  if (IS_ERR(pClass)) {
    printk(KERN_WARNING "\ncan't create class");
    unregister_chrdev_region(devNo, 1);
    return -1;
  }

  // Create /dev/kmem for this char dev
  if (IS_ERR(pDev = device_create(pClass, NULL, devNo, NULL, "kmem"))) {
    printk(KERN_WARNING "devko.ko can't create device /dev/kmem\n");
    class_destroy(pClass);
    unregister_chrdev_region(devNo, 1);
    return -1;
  }
  return 0;
} // end of devkoInit


static void __exit devkoExit(void) {
  // Clean up after ourselves
  device_destroy(pClass, devNo);  // Remove the /dev/kmem
  class_destroy(pClass);  // Remove class /sys/class/kmem
  unregister_chrdev(majorNum, DEVICE_NAME);  // Unregister the device
} // end of devkoExit
like image 103
Ravi Avatar answered Sep 07 '25 22:09

Ravi