linux驅動之Hello World,linuxhelloworld
看了幾天的Windows Internals, 覺得挺煩的,看不進去。作者講Windows的各種機制講得有些枯燥,畢竟Windows不是開源的,很多內部的實現都只能用概念來講解,有些抽象。
轉到了Linux陣營,經典的LDD(Linux Driver Develop)讀起來順暢無比,相見恨晚。
驅動的Hello World,也是好幾天,今天才弄好。其間編譯安裝自己的核心差點把整個系統搞掛,格式不對導致make好幾天莫名其妙錯誤。
首先,我是Ubuntu的,apt還是很方便的。並不需要使用自己編譯的核心,Ubuntu可以直接用apt安裝相關的編譯環境(核心標頭檔和庫檔案)。名字為 linux-headers-核心版本,不知道核心版本也沒事,用下面命令:
$ sudo apt-get install linux-headers-$(uname -r)
然後就可以找個地方編寫我們自己的Hello World代碼了,代碼比較簡單,用vi就好了。
#include <linux/init.h>#include <linux/module.h>#include <linux/kernel.h>static int hello_init(void){printk( KERN_ALERT "Hello, world! I'm Lizhixing.\n" );return 0;};static void hello_exit(void){printk( KERN_ALERT "Good bye, cruel world. Tommorow is another day! \n" );};module_init( hello_init );module_exit( hello_exit );
這段代碼註冊了module載入和卸載的事件處理函數,只列印一下。
只有代碼不能直接用gcc編譯,要寫Makefile檔案。Makefile檔案推薦用vi編寫,省得出錯。
obj-m = hello.oKVERSION = $(shell uname -r)all:make -C /lib/modules/$(KVERSION)/build M=$(PWD) modulesclean:make -C /lib/modules/$(KVERSION)/build M=$(PWD) clean
然後make即可完成編譯。
makemake -C /lib/modules/3.13.0-24-generic/build M=/disks/e/0-code/0-thinkingl-code/trunk/thinkingl-codelib/Study/0-linuxdriver/0-helloworld modulesmake[1]: Entering directory `/usr/src/linux-headers-3.13.0-24-generic' CC [M] /disks/e/0-code/0-thinkingl-code/trunk/thinkingl-codelib/Study/0-linuxdriver/0-helloworld/hello.o Building modules, stage 2. MODPOST 1 modules CC /disks/e/0-code/0-thinkingl-code/trunk/thinkingl-codelib/Study/0-linuxdriver/0-helloworld/hello.mod.o LD [M] /disks/e/0-code/0-thinkingl-code/trunk/thinkingl-codelib/Study/0-linuxdriver/0-helloworld/hello.komake[1]: Leaving directory `/usr/src/linux-headers-3.13.0-24-generic'
然後就可以載入和卸載模組測試效果:
insmod hello.kormmod hello.ko
ssh命令列上可能看不到效果,看dmesg:
[133540.841098] Hello, world! I'm Lizhixing.[133553.819340] Good bye, cruel world. Tommorow is another day!
linux驅動的hello world不可以通過編譯
寫個Makefile就對了:注意tab
obj-m := drv.o
KDIR := /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)
default:
$(MAKE) -C $(KDIR) SUBDIRS=$(PWD) modules
clean:
$(MAKE) -C $(KDIR) SUBDIRS=$(PWD) clean
rm -rf Module.markers modules.order Module.symvers
linux 裝置驅動建立hello world模組
可以不用到源碼目錄下make的,參看以下,以前用過的,好用的
模組源碼檔案led_driver.c
#ifndef __KERNEL__#define __KERNEL__#endif#ifndef MODULE#define MODULE#endif#include <linux/module.h>#include <linux/kernel.h>MODULE_LICENSE("GPL");int init_led_module(void){ printk("Hello led driver!\n"); return 0;}void cleanup_led_module(void){ printk("Goodbye led driver!\n");}MODULE_AUTHOR("ABC");MODULE_LICENSE("Dual BSD/GPL");module_init(init_led_module);module_exit(cleanup_led_module);
makefile檔案
ifneq ($(KERNELRELEASE),)CROSS_COMPILE=ARCH:=x86CC:=$(CROSS_COMPILE)gccLD:=$(CROSS_COMPILE)ldobj-m := led_driver.o elsePWD = $(shell pwd)KVER ?= $(shell uname -r)KDIR := /lib/modules/$(KVER)/builddefault: $(MAKE) -C $(KDIR) M=$(PWD) modulesclean: $(MAKE) -C $(KDIR) M=$(PWD) clean rm -rf .*.cmd *.o *.mod.c *.ko .tmp_versionsendif