Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux 主/次裝置號完整解析:功能、內部表示、巨集、misc 裝置註冊

編輯:Linux 教學

Linux 裝置驅動核心概念:主裝置號識別驅動程式,次裝置號識別具體裝置實例。本文系統解析功能定義、dev_t 內部結構、巨集操作、misc 裝置簡化註冊流程。

1. 功能定義

  • 主裝置號:告訴核心使用哪個驅動程式服務該裝置 (如 /dev/tty0, tty1 主號皆為 4)
  • 次裝置號:驅動程式內部區分不同裝置實例 (tty0 次號 0, tty1 次號 1)
  • 一組 (主,次) 唯一標識一個裝置節點

2. 查看系統已分配主號


cat /proc/devices

3. dev_t 內部表示 (2.6 核心)

  • 32 位元無號長整數:typedef unsigned long dev_t;
  • 高 12 位 = 主裝置號 (擴展自 8 位)
  • 低 20 位 = 次裝置號 (擴展自 8 位)

4. 核心巨集 ()

巨集功能定義
MAJOR(dev_t dev)從 dev_t 取得主號((unsigned int)((dev) >> MINORBITS))
MINOR(dev_t dev)從 dev_t 取得次號((unsigned int)((dev) & MINORMASK))
MKDEV(int major, int minor)由主/次號構建 dev_t(((major) << MINORBITS) | (minor))

5. misc 裝置 (雜項裝置) 簡化註冊

  • 固定主號 = 10 (MISC_MAJOR)
  • 僅需指定次號、名稱、file_operations
  • 註冊/註銷:

misc_register(&miscdev);
misc_deregister(&miscdev);

miscdevice 結構體 ()


struct miscdevice {
    int minor;                  // 次號,MISC_DYNAMIC_MINOR 自動分配
    const char *name;           // 裝置名稱 (顯示於 /dev/name)
    struct file_operations *fops; // 檔案操作結構
    struct miscdevice *next, *prev; // 內部鏈表
    devfs_handle_t devfs_handle;    // 內部
};

實例:動態分配次號的 misc 裝置


static struct miscdevice my_misc = {
    .minor = MISC_DYNAMIC_MINOR,
    .name  = "mymisc",
    .fops  = &my_fops,
};
// 模組初始化呼叫 misc_register(&my_misc);

查看已註冊 misc 裝置


cat /proc/misc

適用場景

  • 單一實例、無複雜分區需求的虛擬/字元裝置 (如 watchdog, rng, 硬體監控)
  • 避免手動分配主號、建立類別、裝置節點的樣板碼

掌握主/次號機制與 misc 裝置,驅動開發入門不再迷路。

Copyright © Windows教程網 All Rights Reserved