LDD2代码阅读手记: hello.c
时间:2006-05-21 来源:lanttor.guo
笔记原创: 兰特
联系邮件: [email protected]
参考资料:
1. Linux Device Drivers, Second Edition, Alessandro
2. The Linux Kernel Module Programming Guide (v2.4.0), Peter Jay Salzman Ori Pomerantz
/*
* $Id: hello.c,v 1.10 2001/07/17 10:30:02 rubini Exp $
*/
#define __KERNEL__
#define MODULE
#include <linux/module.h>
/*
* These lines, although not shown in the book,
* are needed to make hello.c run properly even when
* your kernel has version support enabled
*/
int init_module(void) { printk("<1>Hello, world\n"); return 0; }
void cleanup_module(void) { printk("<1>Goodbye cruel world\n"); }
MODULE_LICENSE("GPL");
这是一个最简单的模块编程的例子,经典的Hello World !
必须在程序前定义一个预处理符号__KERNEL__, 如果没有这个符号,模块就不能使用内核头文件针对内核的特殊内容.
必须在程序前定义一个预处理符号MODULE, 这个符号必须在程序包含<linux/module.h>之前定义(除非驱动程序直接链入内核).
这个符号告诉程序的头文件给内核模块适合的定义.
上述的两个符号既可以在程序前定义, 也可以在Makefile中定义.
init_module()是起始入口函数:当模块被动态加载到内核中时,该函数被调用.
cleanup_module()是结束入口函数:当模块从内核中被动态卸载时,该函数被调用.
printk是内核信息输出函数, 相当于标准库中的printf函数.
MODULE_LICENSE: 发布代码的许可证条款.
编译:
gcc -c -I/usr/src/linux/include hello.c
加入-I/usr/src/linux/include 这一项是因为模块编程属于内核编程,使用的头文件必须是内核的头文件. 而gcc默认的编译头文件是/usr/include,
该头文件是标准库的头文件.
在root用户权限下动态加载编译好的模块: insmod hello.o
用dmesg看输出信息: Hello, Linux World!
卸载模块: rmmod hello
用dmesg看输出信息: Goodbye cruel world
联系邮件: [email protected]
参考资料:
1. Linux Device Drivers, Second Edition, Alessandro
2. The Linux Kernel Module Programming Guide (v2.4.0), Peter Jay Salzman Ori Pomerantz
/*
* $Id: hello.c,v 1.10 2001/07/17 10:30:02 rubini Exp $
*/
#define __KERNEL__
#define MODULE
#include <linux/module.h>
/*
* These lines, although not shown in the book,
* are needed to make hello.c run properly even when
* your kernel has version support enabled
*/
int init_module(void) { printk("<1>Hello, world\n"); return 0; }
void cleanup_module(void) { printk("<1>Goodbye cruel world\n"); }
MODULE_LICENSE("GPL");
这是一个最简单的模块编程的例子,经典的Hello World !
必须在程序前定义一个预处理符号__KERNEL__, 如果没有这个符号,模块就不能使用内核头文件针对内核的特殊内容.
必须在程序前定义一个预处理符号MODULE, 这个符号必须在程序包含<linux/module.h>之前定义(除非驱动程序直接链入内核).
这个符号告诉程序的头文件给内核模块适合的定义.
上述的两个符号既可以在程序前定义, 也可以在Makefile中定义.
init_module()是起始入口函数:当模块被动态加载到内核中时,该函数被调用.
cleanup_module()是结束入口函数:当模块从内核中被动态卸载时,该函数被调用.
printk是内核信息输出函数, 相当于标准库中的printf函数.
MODULE_LICENSE: 发布代码的许可证条款.
编译:
gcc -c -I/usr/src/linux/include hello.c
加入-I/usr/src/linux/include 这一项是因为模块编程属于内核编程,使用的头文件必须是内核的头文件. 而gcc默认的编译头文件是/usr/include,
该头文件是标准库的头文件.
在root用户权限下动态加载编译好的模块: insmod hello.o
用dmesg看输出信息: Hello, Linux World!
卸载模块: rmmod hello
用dmesg看输出信息: Goodbye cruel world
相关阅读 更多 +