歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Linux模塊編程機制之hello kernel

Linux模塊編程機制之hello kernel

日期:2017/3/1 10:26:48   编辑:Linux編程

看了那麼多理論知識,可能還是一頭霧水,是啊,純理論分析本來就不好理解。為了更好的理解Linux內核各種內部機制以及其運用,在接下來的學習中將采用理論+實驗+源碼注釋的方式進行。包括算法、原理的實驗,內核的局部擴展與修改等。Linux內核編程有很多方法,最方便的方式是使用內核提供的模塊編程機制,另一種方式是以補丁的方式,這種方式只需要編譯一次內核,當然也可以直接修改內核源碼,但是每次修改後都需要重新編譯、引導、重啟,很麻煩,也很費時。首先,我們看看最方便快捷的一種方式——LINUX內核中模塊編程機制。

還是從程序員的哪個起步程序hello world開始,但是我們這裡比一般的hello world稍微復雜一點,用兩個hello world程序。

文件hello.c

  1. #include <linux/init.h>
  2. #include <linux/module.h>
  3. #include <linux/kernel.h>
  4. MODULE_LICENSE("GPL");
  5. extern int hello_data;
  6. static int hello_init(void)
  7. {
  8. printk(KERN_ERR "hello,kernel!,this is hello module\n");
  9. printk(KERN_ERR "hello_data:%d\n",++hello_data);
  10. return 0;
  11. }
  12. static void hello_exit(void)
  13. {
  14. printk(KERN_ERR "hello_data:%d\n",--hello_data);
  15. printk(KERN_ERR "Leave hello module!\n");
  16. }
  17. module_init(hello_init);
  18. module_exit(hello_exit);
  19. MODULE_AUTHOR("Mike Feng");
  20. MODULE_DESCRIPTION("This is hello module");
  21. MODULE_ALIAS("A simple example");

對應的Makefile文件:

  1. obj-m +=hello.o
  2. CURRENT_DIR:=$(shell pwd)
  3. KERNEL_DIR:=$(shell uname -r)
  4. KERNEL_PATH:=/usr/src/kernels/$(KERNEL_DIR)
  5. all:
  6. make -C $(KERNEL_PATH) M=$(CURRENT_DIR) modules
  7. clean:
  8. make -C $(KERNEL_PATH) M=$(CURRENT_DIR) clean

文件hello_h.c:

  1. #include <linux/init.h>
  2. #include <linux/module.h>
  3. #include <linux/kernel.h>
  4. MODULE_LICENSE("GPL");
  5. static unsigned int hello_data=100;
  6. EXPORT_SYMBOL(hello_data);
  7. static int hello_h_init(void)
  8. {
  9. hello_data+=5;
  10. printk(KERN_ERR "hello_data:%d\nhello kernel,this is hello_h module\n",hello_data);
  11. return 0;
  12. }
  13. static void hello_h_exit(void)
  14. {
  15. hello_data-=5;
  16. printk(KERN_ERR "hello_data:%d\nleave hello_h module\n",hello_data);
  17. }
  18. module_init(hello_h_init);
  19. module_exit(hello_h_exit);
  20. MODULE_AUTHOR("Mike Feng");

對應的Makefile

  1. obj-m+=hello_h.o
  2. CURRENT:=$(shell pwd)
  3. KERNEL_PATH:=/usr/src/kernels/$(shell uname -r)
  4. all:
  5. make -C $(KERNEL_PATH) M=$(CURRENT) modules
  6. clean:
  7. make -C $(KERNEL_PATH) M=$(CURRENT) clean

可見,我們在hello_h.c中定義了一個靜態變量hello_data,初始值為100,並把他導出了,在hello.c中使用了該變量。這樣給出例子,後面我們會看到,是為了說明模塊依賴。

Copyright © Linux教程網 All Rights Reserved