Linux 设备节点
概述
A device node, device file, or device special file is a type of special file used on many Unix-like operating systems, including Linux.
设备节点、设备文件或设备专用文件是一种在许多类 Unix 操作系统(包括 Linux)上使用的专用文件。
Device nodes facilitate transparent communication between user space applications and computer hardware.
设备节点促进用户空间应用程序和计算机硬件之间的透明通信。
By definition, device nodes correspond to resources that have already been allocated by the operating system Kernel. The resources are identified by a major number and a minor number, which are stored as part of the structure of a node. The assignment of these numbers is specific to different operating systems and computer platforms. Generally, the major number identifies the device driver and the minor number identifies a particular device (possibly out of many) that the driver controls, and is passed to the driver as an argument.
根据定义,设备节点对应于操作系统内核已经分配的资源。 资源由主要编号和次要编号标识,它们作为节点结构的一部分存储。 这些编号的分配特定于不同的操作系统和计算机平台。 通常,主要编号标识设备驱动程序,次要编号标识驱动程序控制的特定设备(可能是许多),并作为参数传递给驱动程序。
Like other special file types, device nodes are accessed using standard system calls and treated like regular files.
与其他特殊文件类型一样,设备节点使用标准系统调用进行访问,并被视为常规文件。
设备节点
Linux 下的设备通常分为三类:字符设备、块设备和网络设备。相对应的,驱动程序也分为三类,即字符设备驱动程序、块设备驱动程序和网络设备驱动程序。
- 常见的字符设备有鼠标、键盘、串口、控制台等,它们的特点是只能顺序访问。
- 常见的块设备有各种磁盘、硬盘、Flash、RAM 等,它们的特点是可以随机访问。
- Linux 中的网络设备是比较特殊的,一个网络设备通常也称为一个网络接口(如 eth0),应用程序并非通过设备节点而是通过 socket 来访问网络设备。
其实在 Linux 系统中根本就不存在网络设备节点(通过 cat /proc/devices 查看只有 Character devices 和 Block devices)。网络接口没有像字符设备和块设备一样的设备号,只有一个唯一的名字,如 eth0、eth1 等,而这个名字也不需要与设备文件节点对应。
设备节点被创建在 /dev 下,是连接内核与用户层的枢纽,就是设备是接到对应哪种接口的哪个 ID 上。 相当于硬盘的 inode一样的东西,记录了硬件设备的位置和信息。在Linux中,所有设备都以文件的形式存放在 /dev 目录下,都是通过文件的方式进行访问,设备节点是 Linux 内核对设备的抽象,一个设备节点就是一个文件。应用程序通过一组标准化的调用执行访问设备,这些调用独立于任何特定的驱动程序。而驱动程序负责将这些标准调用映射到实际硬件的特有操作。
在 /dev 目录下除了字符设备和块设备节点之外,还通常还会存在 FIFO 管道、Socket、软/硬连接、目录等,不过这些东西没有主/次设备号。