Search

Creating a misc characther device and reading from it

Linux has misc devices which meant for small device drivers. According to the article written by Alessandro Rubini Miscellaneous Character Drivers :

Sometimes people need to write “small” device drivers, to support custom hacks—either hardware or software ones. To this end, as well as to host some real drivers, the Linux kernel exports an interface to allow modules to register their own small drivers. The misc driver was designed for this purpose.

miscdevice is declared as the structure in miscdevice.h



For this example we will just use the first three fields.



The name of the device can be any name that the user wants. The minor number can be statically assigned by the user , if it has to be dynamically assigned by the user , the value has to be set to `MISC_DYNAMIC_MINOR.

Thus our device structure will look as below.



To register a misc device the function used is



We can create a characther string which will hold the data for now which will be sent out everytime the device is read. Thus we create a function to fill the data for the device.



The init function for the device will have to register the device. Unlike a charachter device, we dont need to get a major number for a misc device as the default major number for misc devices is 10. To see the minor number which will be assigned dynamically we will add a print statement to get the minor number.



We will create two file operations for this, one to open the device and one to read from the device. Thus the file operations structure will be



The open function will fill data into the device,which we can read using the read function.



The read function will copy the contents of the device to the userspace.



Thus the full code misc device will be



Save the above code as misc_device_read.c

Use the following makefile to compile the code.



Compile and insert the code using



To see the minor number allocated to the device, use dmesg



We can also view the minor number and find if the device got registered succssfully by looking into the file /proc/misc



The device will automatically get listed under /dev which we can view using the ls command.



We can see that the major number is 10 and the minor number is 55.

To read the device, we can use the cat command.




No comments:

Post a Comment