How to create a device in /dev automatically upon loading of the kernel module for a device driver?

Mir picture Mir · Jan 2, 2012 · Viewed 28.5k times · Source

I am attempting to develop Linux device drivers and as my first attempt I am trying to develop a char device driver that has the following file options,

struct file_operations fops{  
.open=open_fun,  
.release=release_fun,  
.write=write_fun,  
.read=read_fun,  
};  

When I load the driver using insmod, I see that /proc/devices lists the driver under char devices but I can't find it in /dev. A Google search suggested use of mknod to create a deivce in /dev and associate it with the driver's major and minor. However, an attempt to do so resulted in "Permission denied" error even when done as a super user.

What should I do to make the device appear in /dev when the kernel module is loaded? I tried both the older (register_chrdev) and the newer version (cdev_init & cdev_add) of registering the device but none of them works.

Thanks,
Mir

Answer

Harish Venkatesan picture Harish Venkatesan · Feb 2, 2017
  • Include the header file linux/device.h and linux/kdev_t.h

  • static struct class c_dev;

  • static struct dev_t dev;

Add the below API 's inside __init fuction of the driver

  • cl = class_create(THIS_MODULE ,"x");

where x - Name to be displayed inside /sys/class/ when driver is loaded.

  • Use device_create () kernel api with device_create(cl, NULL, dev, NULL, "d");

where d - device file to be created under /dev.

where dev is variable for the first device number that is initialized during the usage of alloc_chrdev_region API for dynamic allocation of major number for the driver

For Further reference please go through the link http://opensourceforu.com/2011/04/character-device-files-creation-operations/