printk() 使用示例
时间: 2023-12-13 10:03:11 浏览: 35
下面是一个简单的 printk() 使用示例:
```c
#include <linux/kernel.h>
#include <linux/module.h>
int init_module(void)
{
printk(KERN_INFO "Hello, World!\n");
printk(KERN_WARNING "This is a warning message.\n");
printk(KERN_ERR "An error occurred.\n");
return 0;
}
void cleanup_module(void)
{
printk(KERN_INFO "Goodbye, World!\n");
}
```
在这个示例中,我们在内核模块中使用了 printk() 函数来打印不同级别的信息。
- `KERN_INFO` 表示普通的信息级别,用来输出 "Hello, World!" 和 "Goodbye, World!"。
- `KERN_WARNING` 表示警告级别,用来输出警告信息 "This is a warning message."。
- `KERN_ERR` 表示错误级别,用来输出错误信息 "An error occurred."。
在编译和加载模块后,你可以使用 `dmesg` 命令来查看内核日志,以查看打印出来的信息。
注意:此示例是一个简单的内核模块,需要在 Linux 内核环境中编译和加载运行。
相关问题
Linux内核链表使用示例
下面是一个简单的使用 Linux 内核链表的示例:
```c
#include <linux/list.h>
#include <linux/module.h>
#include <linux/kernel.h>
struct student {
int id;
char name[20];
struct list_head list;
};
static LIST_HEAD(students);
int __init my_module_init(void)
{
struct student *s1, *s2, *s3, *s4, *tmp;
s1 = kmalloc(sizeof(struct student), GFP_KERNEL);
s1->id = 1001;
strncpy(s1->name, "Alice", sizeof(s1->name));
INIT_LIST_HEAD(&s1->list);
list_add_tail(&s1->list, &students);
s2 = kmalloc(sizeof(struct student), GFP_KERNEL);
s2->id = 1002;
strncpy(s2->name, "Bob", sizeof(s2->name));
INIT_LIST_HEAD(&s2->list);
list_add_tail(&s2->list, &students);
s3 = kmalloc(sizeof(struct student), GFP_KERNEL);
s3->id = 1003;
strncpy(s3->name, "Charlie", sizeof(s3->name));
INIT_LIST_HEAD(&s3->list);
list_add_tail(&s3->list, &students);
s4 = kmalloc(sizeof(struct student), GFP_KERNEL);
s4->id = 1004;
strncpy(s4->name, "David", sizeof(s4->name));
INIT_LIST_HEAD(&s4->list);
list_add_tail(&s4->list, &students);
printk(KERN_INFO "List of students:\n");
list_for_each_entry(tmp, &students, list) {
printk(KERN_INFO "ID: %d, Name: %s\n", tmp->id, tmp->name);
}
return 0;
}
void __exit my_module_exit(void)
{
struct student *tmp, *next;
list_for_each_entry_safe(tmp, next, &students, list) {
list_del(&tmp->list);
kfree(tmp);
}
}
module_init(my_module_init);
module_exit(my_module_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Your Name");
MODULE_DESCRIPTION("Linux Kernel Linked List Example");
```
该示例定义了一个名为 `student` 的结构体,其中包含学生的 ID 和姓名,并使用内核链表将多个学生添加到了一个链表中。在模块初始化期间,代码分配了一些内存来存储学生的信息,并将它们添加到链表中。最后,它遍历链表并使用 `printk` 函数打印每个学生的 ID 和姓名。
在模块退出期间,所有分配的内存都将被释放,并且链表的所有元素都将被删除。
printk_once
printk_once是一个宏定义,它的作用是在内核中只打印一次指定的日志信息。在引用中的宏定义中,它使用了一个静态变量__print_once来记录是否已经打印过该信息,如果没有打印过,则打印该信息并将__print_once设置为true,否则不做任何操作。在引用中的代码中,printk_once被用来打印一条日志信息,并且只会在第一次调用该函数时打印。
代码示例:
```c
#define printk_once(x...) ({ \
static bool __print_once; \
\
if (!__print_once) { \
__print_once = true; \
printk(x); \
} \
})
void my_function() {
printk_once(KERN_INFO "This message will only be printed once.\n");
}
```