內核第一個程序之Hello World!

這個程序是《Linux device drivers》中的代碼片斷:html

#include <linux/init.h>
#include <linux/module.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, 建議去看一下makefile的基本語法,$(MAKE) -C $(KERNELDIR) SUBDIRS = $(PWD) modules這句就是說首先改變目錄到-C選項指定的目錄(即內核源代碼目錄),其中保存了內核的頂層makefile文件。SUBDIRS=選項讓該makefile在構造modules目標返回以前到模塊源代碼目錄。而後,modules目標指向obj-m變量設定的模塊。linux

ifneq ($(KERNELRELEASE),)
     obj-m := hello.o
else
     KERNELDIR :=/lib/modules/$(shell uname -r)/build
     PWD := $(shell pwd)
all:
     $(MAKE) -C $(KERNELDIR) SUBDIRS=$(PWD) modules
endif
clean:
     rm -f *.o *.ko *.mod.c .hello*

好了,而後安逸的make一下:shell

make -C /lib/modules/3.13.0-35-generic/build SUBDIRS=/home/zachery/kernel_programming modules
make[1]: Entering directory `/usr/src/linux-headers-3.13.0-35-generic'
  CC [M]  /home/zachery/kernel_programming/hello.o
  Building modules, stage 2.
  MODPOST 1 modules
  CC      /home/zachery/kernel_programming/hello.mod.o
  LD [M]  /home/zachery/kernel_programming/hello.ko
make[1]: Leaving directory `/usr/src/linux-headers-3.13.0-35-generic'
 

接下來能夠看效果了,ui

裝載模塊: insmod ./hello.kospa

卸載模塊: rmmod hello日誌

terminal是看不到輸出的,消息進入了其中一個系統日誌文件中, 我當前的Ubuntu14.04是 /var/log/syslog (實際文件名子隨 Linux 發佈而變化). 可使用 tail -f /var/log/syslog查看。code

 

ps: printk中優先級只是一個字串, 前綴於 printk 格式串以前. 注意在 KERN_ALERT 後面是不須要逗號的!!htm

相關文章
相關標籤/搜索