116 lines
1.9 KiB
Markdown
116 lines
1.9 KiB
Markdown
|
# Linux Kernel 字符设备接口函数
|
|||
|
|
|||
|
**头文件:**
|
|||
|
|
|||
|
```cpp
|
|||
|
#include <linux/cdev.h>
|
|||
|
```
|
|||
|
|
|||
|
## MKDEV
|
|||
|
|
|||
|
**函数原型:**
|
|||
|
|
|||
|
```cpp
|
|||
|
#define MKDEV(major,minor) (((major) << MINORBITS) | (minor))
|
|||
|
```
|
|||
|
|
|||
|
**说明:**
|
|||
|
|
|||
|
将主设备号和次设备号转换成 dev_t 类型。
|
|||
|
|
|||
|
**参数:**
|
|||
|
|
|||
|
major:主设备号。
|
|||
|
|
|||
|
minor:次设备号。
|
|||
|
|
|||
|
**返回值:**
|
|||
|
|
|||
|
dev_t 类型的设备号。
|
|||
|
|
|||
|
## register_chrdev_region
|
|||
|
|
|||
|
**函数原型:**
|
|||
|
|
|||
|
```cpp
|
|||
|
int register_chrdev_region(dev_t from, unsigned count, const char *name);
|
|||
|
```
|
|||
|
|
|||
|
**说明:**
|
|||
|
|
|||
|
向内核申请注册设备号。
|
|||
|
|
|||
|
**参数:**
|
|||
|
|
|||
|
from:dev_t 形式的设备号,可由 MKDEV 创建。
|
|||
|
|
|||
|
count:申请次设备号的个数。
|
|||
|
|
|||
|
name:设备名称。执行 cat /proc/devices 时会显示该名称。
|
|||
|
|
|||
|
**返回值:**
|
|||
|
|
|||
|
成功返回 0,否则返回错误码。
|
|||
|
|
|||
|
## alloc_chrdev_region
|
|||
|
|
|||
|
**函数原型:**
|
|||
|
|
|||
|
```cpp
|
|||
|
int alloc_chrdev_region(dev_t *dev, unsigned baseminor, unsigned count, const char *name)
|
|||
|
{
|
|||
|
struct char_device_struct *cd;
|
|||
|
cd = __register_chrdev_region(0, baseminor, count, name);
|
|||
|
if (IS_ERR(cd))
|
|||
|
return PTR_ERR(cd);
|
|||
|
*dev = MKDEV(cd->major, cd->baseminor);
|
|||
|
return 0;
|
|||
|
}
|
|||
|
```
|
|||
|
|
|||
|
**说明:**
|
|||
|
|
|||
|
动态分配主设备号。
|
|||
|
|
|||
|
**参数:**
|
|||
|
|
|||
|
dev:返回函数向内核申请下来的设备号。
|
|||
|
|
|||
|
baseminor:起始次设备号。
|
|||
|
|
|||
|
count:申请次设备号的个数。
|
|||
|
|
|||
|
name:设备名称。执行 cat /proc/devices 时会显示该名称。
|
|||
|
|
|||
|
**返回值:**
|
|||
|
|
|||
|
成功返回 0,否则返回错误码。
|
|||
|
|
|||
|
## cdev_init
|
|||
|
|
|||
|
**函数原型:**
|
|||
|
|
|||
|
```cpp
|
|||
|
void cdev_init(struct cdev *cdev, const struct file_operations *fops)
|
|||
|
{
|
|||
|
memset(cdev, 0, sizeof *cdev);
|
|||
|
INIT_LIST_HEAD(&cdev->list);
|
|||
|
kobject_init(&cdev->kobj, &ktype_cdev_default);
|
|||
|
cdev->ops = fops;
|
|||
|
}
|
|||
|
```
|
|||
|
|
|||
|
**说明:**
|
|||
|
|
|||
|
关联 cdev 和 file_operations
|
|||
|
|
|||
|
**参数:**
|
|||
|
|
|||
|
cdev:字符设备对象
|
|||
|
|
|||
|
fops:设备操作方法
|
|||
|
|
|||
|
**返回值:**
|
|||
|
|
|||
|
无
|