1. 程式人生 > >Linux內核編程-0:來自內核的 HelloWorld

Linux內核編程-0:來自內核的 HelloWorld

軟件 內核編程 生成 x86_64 int urn bye rmmod dev

Linux內核編程一直是我很想掌握的一個技能。如果問我為什麽,我也說不上來。
也許是希望有一天自己的ID也出現在內核開發組的郵件列表裏?或是內核發行文件的CREDITS文件上?
也許是吧。其實更多的,可能是對於底層的崇拜,以及對於內核的求索精神。
想到操作系統的繁雜,想到軟件系統之間的銜接,內心覺得精妙的同時,更是深深的迷戀。
所以從這篇文章開始,我要真正的走進Linux內核裏了,讓代碼指引我,去奇妙的世界一探究竟。

在這篇文章中,一起來對內核說Hello World。
本次的編程環境:
CentOS 6.8

Linux centos 2.6.32-573.8.1.el6.x86_64

沒有安裝內核的,可能需要安裝一下內核源碼包

kernel-devel-2.6.32-642.4.2.el6.x86_64

yum install kernel-devel-2.6.32-642.4.2.el6.x86_64

安裝好之後,這個版本內核可以在/usr/src/linux找到。

然後先話不多說,首先看代碼。

//20160904
//kernel_hello_world.c

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>

static int __init lkp_init(void){
    printk("Hello,World! --from the kernel space...\n");
    return 0;
}

static void __exit lkp_cleanup(void){
    printk("Goodbye,World! --leaving kernel space...");
}

module_init(lkp_init);
module_exit(lkp_cleanup);

以上代碼是kernel_hello_world.c內容。
作為內核模塊,在編譯的時候,Makefile文件這樣寫:

#File:Makefile
obj-m += kernel_hello_world.o

然後可以通過這條命令來編譯:

make -C /usr/src/linux SUBDIRS=$PWD modules

編譯好以後,目錄下面的文件可能是這樣子:

kernel_hello_world.ko.unsigned  kernel_hello_world.o  Module.symvers
kernel_hello_world.c   kernel_hello_world.mod.c        Makefile
kernel_hello_world.ko  kernel_hello_world.mod.o        modules.order

有這麽多文件被生成,其中kernel_hello_world.ko就是本次編譯出來的內核模塊文件,在Linux內核中有很多這樣的模塊,它們可能充當著不同的角色,可能是驅動,也可能是各種設備。
這個模塊會在/var/log/message文件中打印一行字,即Hello,World! --from the kernel space...
可以使用insmod kernel_hello_world.ko來將這個模塊載入到內核。
使用lsmod來查看是否已經加載。
使用rmmod kernel_hello_world.ko來卸載這個模塊。
可以tail /var/log/message來看一下是否成功執行了呢?

Hello,Kernel.

Linux內核編程-0:來自內核的 HelloWorld