在内核模块中使用current宏

在Linux平台下,每一个进程都有一个task_struct数据结构,用来存储该进程的相关信息。task_struct在内核的以下代码中定义(以2.6.36为例,其他类似):http://lxr.linux.no/linux+v2.6.27/include/linux/sched.h。

task_struct最简单的两个成员,其他的这里就不再介绍了:
进程名称
点击隐藏
C CODE1153
1154
1155
1156            char comm[TASK_COMM_LEN]; /* executable name excluding path
                                     - access with [gs]et_task_comm (which lock
                                       it with task_lock())
                                     - initialized normally by flush_old_exec */

进程号
点击隐藏
C CODE1091            pid_t pid;

在内核模块中,可以通过调用current来获取当前进程的task_struct数据结构,调用方式如下:
点击隐藏
C CODE1    printf("Task name: %s, task ID: %d\n", current->comm, current->pid);

current是在中定义的:
点击隐藏
C CODE1
2
3
4
5
6
7
8
9
10    #ifndef __ASM_GENERIC_CURRENT_H
#define __ASM_GENERIC_CURRENT_H
#include <linux /thread_info.h>
#define get_current() (current_thread_info()->task)
#define current get_current()
#endif /* __ASM_GENERIC_CURRENT_H */
</linux>

所以在调用current之前,需要首先包含该头文件,但是需要注意的是,如果只包含该头文件,程序就会在链接的过程中出现以下错误:
dereferencing pointer to incomplete type
错误位置就在current调用的时候。原因很简单但是大家却容易忽略,就是current只是一个宏定义而已,实际执行还是由task_struct结构体来完成,没有包含结构体task_struct的定义,自然就会出现“定义不完全”的错误了。所以在调用之前需要包含<linux/sched.h>头文件,其中包含task_struct结构体的定义。
完整的current使用方法如下:
点击隐藏
C CODE1
2
3
4
5
6
7
8    #include <asm -generic/current.h>
#include <linux /sched.h>
void show_current(void)
{
printf("Task name: %s, task ID: %d\n", current->comm, current->pid);
}
</linux></asm>

这样,我们就可以通过current获取当前进程的所有信息了。

posted @ 2011-01-09 14:43  羽落无声  阅读(4187)  评论(0编辑  收藏  举报