ubuntu helloworld 驅動編譯,運行。

使用環境 ubuntu18.04桌面版本

原本覺得這類的文章沒什麼太大的價值,早就被普及。結果明明記起來以前寫這麼個demo,現在卻不知道從何下手,所以這裏重新記錄一遍,也是作爲重新進入linux驅動開發的開篇。
要編譯一個hello.ko,我們需要一個已經編譯過的內核源碼環境,當前我的ubuntu18.04,看來是默認有源碼的。
在 /usr/src/目錄下有當前release版本的源碼文件 (只有目錄結構和頭文件)
運行命令#uname -r

root@can-virtual-machine:/work/driver/hello# uname
Linux
root@can-virtual-machine:/work/driver/hello# uname -r
4.15.0-50-generic
root@can-virtual-machine:/work/driver/hello# uname --help
用法:uname [選項]...
輸出一組系統信息。如果不跟隨選項,則視爲只附加-s 選項。

  -a, --all			以如下次序輸出所有信息。其中若-p 和
				-i 的探測結果不可知則被省略:
  -s, --kernel-name		輸出內核名稱
  -n, --nodename		輸出網絡節點上的主機名
  -r, --kernel-release		輸出內核發行號
  -v, --kernel-version     print the kernel version
  -m, --machine            print the machine hardware name
  -p, --processor          print the processor type (non-portable)
  -i, --hardware-platform  print the hardware platform (non-portable)
  -o, --operating-system   print the operating system
      --help		顯示此幫助信息並退出
      --version		顯示版本信息並退出

GNU coreutils online help: <http://www.gnu.org/software/coreutils/>
請向<http://translationproject.org/team/zh_CN.html> 報告uname 的翻譯錯誤
Full documentation at: <http://www.gnu.org/software/coreutils/uname>
or available locally via: info '(coreutils) uname invocation'

//存在對應的源碼
root@can-virtual-machine:/work/driver/hello# ls /usr/src/linux-headers-4.15.0-50-generic/
arch   certs   Documentation  firmware  include  ipc     Kconfig  lib       mm              net      scripts   sound  tools   usr   zfs
block  crypto  drivers        fs        init     Kbuild  kernel   Makefile  Module.symvers  samples  security  spl    ubuntu  virt

參照的《linux設備驅動程序》第二章介紹的hello模塊,(這本中文版的,確實如果按照正常閱讀習慣很多都讀不通順,所以只能結合上下文“略讀”了)。

建一個目錄,添加以下兩個文件,一個hello.c源文件,和makefile文件。

/*
* hello.c
*/
#include <linux/module.h>
#include <linux/init.h>
MODULE_LICENSE("Dual BSD/GPL");

static int hello_init(void)
{
	printk(KERN_ALERT"Hello, world\n");
	return 0;
}


static void hello_exit(void)
{
	printk(KERN_ALERT"Goodbye, cruel world\n");
}

module_init(hello_init);
module_exit(hello_exit);
#makefile 
obj-m:=hello.o
	KERNELBUILD :=/lib/modules/$(shell uname -r)/build
default:
	make -C $(KERNELBUILD) M=$(shell pwd) modules
clean:
	rm -rf *.o *.ko *.mod.c .*.cmd *.markers *.order *.symvers *tmp_versions

obj-m後面跟的就是最終的模塊名,hello, make 會在該目錄下自動找到hello.c文件進行編譯
hello模塊可能依賴多個文件或者模塊,那麼在obj-m後面就可以添加下面語句hello-objs:=file.o file1.o
modules目標指向obj-m變量中設定的模塊

#make
#insmod ./hello.ko
#lsmod | grep "hello"
#rmmod hello

printk打印的內核信息不會再虛擬終端上輸出,一般情況下,kernel信息和sys信息被保存在/var/log/ 目錄下的kern.log和sys.log,查看可以看到hello模塊加載時的hello world 輸出:
#cat /var/log/syslog | head -100  //輸出了頭100行,看到了hello world, 也可以直接grep

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章