1. 引入標頭檔

    在撰寫 driver 前必須先 include 一些標頭檔:

    #include <linux/init.h>
    #include <linux/kernel.h>
    #include <linux/module.h>
    #include <linux/fs.h>

  2. 撰寫控制元件的函式

    struct file_operations 即為定義各個 function pointer 的 structure。

    static ssize_t drv_read(struct file *filp, char *buf, size_t count, loff_t *ppos)
    {
    printk("device read\n");
    return count;
    }

    static ssize_t drv_write(struct file *filp, const char *buf, size_t count, loff_t *ppos)
    {
    printk("device write\n");
    return count;
    }

    static int drv_open(struct inode *inode, struct file *filp)
    {
    printk("device open\n");
    return 0;
    }

    int drv_ioctl(struct inode *inode, struct file *filp, unsigned int cmd, unsigned long arg)
    {
    printk("device ioctl\n");
    return 0;
    }

    static int drv_release(struct inode *inode, struct file *filp)
    {
    printk("device close\n");
    return 0;
    }
  3.   struct file_operations 即為定義各個 function pointer 的 structure。


    struct file_operations drv_fops =
    {
    read: drv_read,
    write: drv_write,
    ioctl: drv_ioctl,
    open: drv_open,
    release: drv_release,
    };
  4. 撰寫初始化、結束元件的函式

    #define MAJOR_NUM          60
    #define MODULE_NAME "DEMO"
    static int demo_init(void) {
    if (register_chrdev(MAJOR_NUM, "demo", &drv_fops) < 0)
    {
    printk("<1>%s: can't get major %d\n", MODULE_NAME, MAJOR_NUM);
    return (-EBUSY);
    }
    printk("<1>%s: started\n", MODULE_NAME);
    return 0;
    }
    static void demo_exit(void) {
    unregister_chrdev(MAJOR_NUM, "demo");
    printk("<1>%s: removed\n", MODULE_NAME);
    }
    module_init(demo_init);
    module_exit(demo_exit);

    其中 MAJOR_NUM 即為 driver 所對應的 device 的 major number

    全站熱搜

    pcman 發表在 痞客邦 留言(0) 人氣()