使用GDK8编译驱动

主要步骤:

  1. 编写一个小的驱动程序,如下所示。
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/proc_fs.h>
#include <linux/version.h>
#include <linux/kernel.h>
#include <linux/init.h>

static struct proc_dir_entry *proc_otg_entry = NULL;
static ssize_t proc_otg_read(struct file *filp, char __user *buf, size_t count, loff_t *offp)
{
    int n = 0, ret;
    char secrets[100];

    sprintf(secrets, "kernel secrets %s\n", filp->f_path.dentry->d_iname);
    n = strlen(secrets);
    if(*offp < n)
    {
        *offp = n+1;
        ret = n+1;
    }
    else
        ret = 0;

    return ret;
}
static ssize_t proc_otg_write(struct file *file, const char __user *buffer,
    size_t count, loff_t *data)
{
    char cmd[100] = { 0x00 };
    int i = 0;

    if (count < 1)
    {
        printk("count <=1\n");
        return -1;
    }
    if (count > sizeof(cmd))
    {
        printk("count > sizeof(cmd)\n");
        return -2;
    }

    return i;
}
#if LINUX_VERSION_CODE >= KERNEL_VERSION(5,6,0)
static const struct proc_ops proc_otg_fops = {
 .proc_read = proc_otg_read,
 .proc_write = proc_otg_write,
};
#else
static const struct file_operations proc_otg_fops = {
 .owner = THIS_MODULE,
 .read  = proc_otg_read,
 .write = proc_otg_write,
};
#endif

static int __init otg_init(void)
{
    proc_otg_entry = proc_create("otg_usb", 0, NULL, &proc_otg_fops);

    return 0;
}
static void __exit otg_exit(void)
{
    if(proc_otg_entry)
        proc_remove(proc_otg_entry);
}
module_init(otg_init);
module_exit(otg_exit);

MODULE_LICENSE("GPL");
  1. 编写一个简易的Makefile;如下所示。
MODULE = otg

obj-m := $(MODULE).o 

all:
    make -C /lib/modules/$(shell uname -r)/build M=$(shell pwd) modules

$(MODULE)-objs := main.o otg.o

clean:
    rm -rf *.o *~ .*.cmd *.ko *.mod.c *.order *.symvers .tmp_versions built-in.o
  1. 在命令行内执行make,进行编译,等待完成编译;如下所示。
  2. 在命令行内输入insmod otg.ko,加载内核模块;可以输入lsmod | grep otg查看信息;如下图所示。
作者:admin  创建时间:2021-11-26 11:05
最后编辑:admin  更新时间:2024-07-16 16:22