Skip to content

Instantly share code, notes, and snippets.

@creamidea
Created April 15, 2013 10:21
Show Gist options
  • Save creamidea/5387156 to your computer and use it in GitHub Desktop.
Save creamidea/5387156 to your computer and use it in GitHub Desktop.
这个是声明全局(外部可以使用,修改的)变量,数组和函数的实例程序代码。 linux内核模块编程。
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/moduleparam.h> /* Param header */
#define DRIVER_AUTHOR "icecream <creamidea@gmail.com>"
#define DRIVER_DESC "A sample driver"
/* 全局变量的声明 */
static int count = 0;
static char* name = "Hello, icecream";
/* 使用这个函数module_param()进行全局变量声明 */
/* 整个系统可以使用,也就是外界可以修改 */
/* 外界这么使用sudo insmod param.ko count=100 name="qooni" */
/* 参考文档系统头文件
* /usr/src/linux-headers-3.5.0-23-generic/include/linux/moduleparam.h */
module_param(count, int, 0644);
module_param(name, charp, 0644);
/* 全局数组的声明 */
static int array[] = {1,9,9,1,1,0,0,4};
static int length = 8;
static int sum = 0;
module_param_array(array, int, &length, 0644);
/* 全局函数的声明 */
/* 函数参数需要指明void */
void myfun(void)
{
printk("my fun is invoked!\n");
}
/* 全局声明 */
EXPORT_SYMBOL(myfun);
static int __init export_init(void)
{
/////////////////////////////////
/* 局部声明必须放在最前面 */
int a = 10;
int b = 12;
int i = 0;
printk("a + b = %d\n", (a+b));
printk("count = %d\n", count);
printk("name = %s\n", name);
/////////////////////////////////
for (i = 0; i < length; ++i) {
sum += array[i];
printk("Array[%d]: %d\n", i, array[i]);
}
/* printk the sum at the module remove mode */
/////////////////////////////////
myfun();
return 0;
}
static void __exit export_exit(void)
{
printk("The sum of the array is %d\n", sum);
printk("Exit the driver module!\n");
}
module_init(export_init); /* enter */
module_exit(export_exit); /* out */
MODULE_LICENSE("Dual BSD/GPL");
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_ALIAS("First Module");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment