试一试 Ubuntu 下编译第一个 Hello World 驱动并运行
https://www.geeksforgeeks.org/linux-kernel-module-programming-hello-world-program/
hello.c:
/**
* @file hello.c
* @author Akshat Sinha
* @date 10 Sept 2016
* @version 0.1
* @brief An introductory "Hello World!" loadable kernel
* module (LKM) that can display a message in the /var/log/kern.log
* file when the module is loaded and removed. The module can accept
* an argument when it is loaded -- the name, which appears in the
* kernel log files.
*/
#include <linux/module.h> /* Needed by all modules */
#include <linux/kernel.h> /* Needed for KERN_INFO */
#include <linux/init.h> /* Needed for the macros */
///< The license type -- this affects runtime behavior
MODULE_LICENSE("GPL");
///< The author -- visible when you use modinfo
MODULE_AUTHOR("Akshat Sinha");
///< The description -- see modinfo
MODULE_DESCRIPTION("A simple Hello world LKM!");
///< The version of the module
MODULE_VERSION("0.1");
static int __init hello_start(void)
{
printk(KERN_INFO "Loading hello module...\n");
printk(KERN_INFO "Hello world\n");
return 0;
}
static void __exit hello_end(void)
{
printk(KERN_INFO "Goodbye Mr.\n");
}
Makefile:
obj-m = hello.o
all:
make -C /lib/modules/$(shell uname -r)/build/ M=$(PWD) modules
clean:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
编译,安装驱动,查看log:
ubuntu@ubuntu:/opt/test3$ make
make -C /lib/modules/5.4.0-42-generic/build/ M=/opt/test3 modules
make[1]: Entering directory '/usr/src/linux-headers-5.4.0-42-generic'
CC [M] /opt/test3/hello.o
Building modules, stage 2.
MODPOST 1 modules
CC [M] /opt/test3/hello.mod.o
LD [M] /opt/test3/hello.ko
make[1]: Leaving directory '/usr/src/linux-headers-5.4.0-42-generic'
ubuntu@ubuntu:/opt/test3$
ubuntu@ubuntu:/opt/test3$ sudo insmod hello.ko
ubuntu@ubuntu:/opt/test3$
ubuntu@ubuntu:/opt/test3$ dmesg |tail -n 1
[256200.240481] Hello world
ubuntu@ubuntu:/opt/test3$
离线