The device drivers under Linux are organized into a set of functions that perform different tasks, making Linux devices operate as if they were files. In an application's view, a hardware device is just a device file, and an application can operate on a hardware device like an ordinary file, such as open (), close (), read (), write (), and so on.
Linux mainly divides the devices into two categories: character devices and block devices. A character device is a device that sends and receives data in the form of characters, while a block device takes the form of an entire data buffer. The drive for character devices is relatively simple.
Let's assume a very simple virtual character device: This device has only a 4-byte global variable int global_var, and the device is named "Globalvar". The operation of "Globalvar" device reads and writes is the operation of the global variable Global_var.
The driver is part of the kernel, so we need to add a module initialization function that completes the initialization of the controlled device and calls the Register_chrdev () function to register the character device:
static int __init globalvar_init (void)
{
if (Register_chrdev (Major_num, "Globalvar", &gobalvar_fops))
{
///... Registration failed
}
else
{
//... Registration succeeded
}
}
Among them, the parameters in the Register_chrdev function major_num The main device number, "Globalvar" is the device name, Globalvar_fops is the structure containing the entry point of the basic function, and the type is file_operations. When the Globalvar module is loaded, the globalvar_init is executed, which calls the kernel function Register_chrdev, which holds the driver's basic entry point pointer in the kernel's character device Address table, providing the entry address when the user process performs a system call on the device.
corresponding to the module initialization function is the module unload function, which needs to invoke the "inverse function" of Register_chrdev ().
Unregister_chrdev ():
static void __exit globalvar_exit (void)
{
if (Unregister_chrdev major_num, " Globalvar "))
{
//... Uninstall failed
}
else
{
//... Uninstall succeeded
}
}