Linux简单的hello模块实现

hello.c

/* hello.c */
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
MODULE_LICENSE("GPL");
MODULE_AUTHOR("tang");
static int hello_init(void)
{
    printk(KERN_ALERT "Hello, world\n");
    return 0;
}
static void hello_exit(void)
{
    printk(KERN_ALERT "Goodbye, hello\n");
}
module_init(hello_init);
module_exit(hello_exit);


Makefile

/* Makefile*/
PWD := $(shell pwd)
KVER := $(shell uname -r)
KDIR := /lib/modules/$(KVER)/build
obj-m:=hello.o
all :
    $(MAKE) -C $(KDIR) SUBDIRS=$(PWD)
.PHONY : clean
clean :
    rm -rf .*.cmd *.mod.c *.o *.ko .tmp_versions

输入命令

make

root@Ubuntu:/home/tang/ty/hello# make
make -C /lib/modules/2.6.32-29-generic/build SUBDIRS=/home/tang/ty/hello
make[1]: Entering directory `/usr/src/linux-headers-2.6.32-29-generic'
  CC [M]  /home/tang/ty/hello/hello.o
  Building modules, stage 2.
  MODPOST 1 modules
  CC      /home/tang/ty/hello/hello.mod.o
  LD [M]  /home/tang/ty/hello/hello.ko
make[1]: Leaving directory `/usr/src/linux-headers-2.6.32-29-generic'


利用insmod加载helloworld模块

insmod hello. ko

利用lsmod命令查看已加载模块


lsmod | grep hello

显示:

hello                    680  0

通过rmmod命令,将helloworld模块从内核中移走

rmmod hello. ko

再次查看

lsmod | grep hello

相关推荐