驅動入門hello執行個體解析

來源:互聯網
上載者:User

首先在終端vim一個檔案名稱為hello.c,輸入內容如下:

  1 #include <linux/module.h>
  2 #include <linux/init.h>
  3 
  4 MODULE_LICENSE("GPL");
  5 MODULE_AUTHOR("Snooy");
  6 
  7 static int howmany = 10;
  8 module_param(howmany,int,S_IRUGO);
  9 
 10 static char *name = "Snooy";
 11 module_param(name,charp,S_IRUGO);
 12 
 13 static __init int hello_init(void) //只被用一次就丟棄__init
 14 {
 15     int i = 0;
 16     for(; i<howmany; i++)
 17         printk(KERN_EMERG"this is %s!\n",name);
 18     return 0;
 19 }
 20 
 21 static __exit void hello_exit(void)
 22 {
 23     printk("<0>goodbye!\n");
 24 }
 25 
 26 module_init(hello_init); //module_...是一個宏
 27 module_exit(hello_exit);
 28 //另一種寫法如下:
 29 //若不要18/19行,則7,13行可改為函數的如下:
 30 //int init_module(void) 函數調運
 31 //void exit_module(void)  函數調運

編寫編譯需要的Makefile(注意這裡好像必須大寫M,否則報錯),內容如下:

  1 ifeq ($(KERNELRELEASE),)
  2     KERNELDIR ?= /usr/src/kernels/2.6.18-164.el5-i686/         #這裡的路徑依據自己虛擬機器linux版本決定(查看指令:uname -r)
  3     PWD := $(shell pwd)   #這裡擷取帶擴充的路徑
  4 modules:
  5     $(MAKE) -C $(KERNELDIR) M=$(PWD) modules
  6 
  7 .PHONY: clean
  8 clean:
  9     rm -rf *.ko *.o Module* *.mod*
 10 else
 11     obj-m := hello.o
 12 endif

解釋:該Makefile在執行make時會進入兩次,具體自己根據if等理解。

使用指令:

insmod hello.ko  安裝模組

lsmod 查看已安裝模組

rmmod hello 或 rmmod hello.ko 刪除模組

dmesg  查看模組運行資訊(最後幾行),或者查看cat  /var/log/messages資訊也行。

到此一個簡單的入門驅動模組編寫安裝與體驗結束。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.