Linux内核 current_thread_info()

函数:current_thread_info( )

文件包含:

        #include <asm/thread_info.h>

函数定义:

在内核源码中的位置:linux-3.19.3/arch/x86/include/asm/thread_info.h函数定义格式:

static inline struct thread_info *current_thread_info(void)
{
        struct thread_info *ti;
        ti = (void*) (this_cpu_read_stable(kernel_stack) +
                      KERNEL_STACK_OFFSET - THREAD_SIZE);
        return ti;
}

函数功能描述:

获取当前进程的基本信息,此信息保存在内核栈中,通过计算内核栈地址的偏移量,获取进程基本信息的地址,并将地址返回给struct thread_info结构体类型的变量,完成将信息保存在结构体变量中的作用。

输入参数说明:

此函数的参数类型是void类型,即不需要任何参数。

返回参数说明:

此函数的返回值类型是struct thread_info类型的指针,定义见文件linux-3.19.3/arch/x86/include/asm/thread_info.h,内容如下:

struct thread_info {
    struct task_struct      *task;                   /*任务描述符*/
    struct exec_domain      *exec_domain;            /*执行域*/
    __u32                   flags;                    /*标志位 */
    __u32                   status;                   /*任务状态位*/
    __u32                   cpu;                      /*当前CPU*/
    int                     saved_preempt_count;      /*抢占计数器*/
    mm_segment_t            addr_limit;
    struct restart_block restart_block;
    void __user             *sysenter_return;
    unsigned int            sig_on_uaccess_error:1;
    unsigned int            uaccess_err:1;
};

实例解析:

编写测试文件:current_thread_info.c

头文件引用:

#include <linux/module.h>
#include <linux/sched.h>
#include <linux/pid.h>
#include <asm/thread_info.h>
#include <linux/kthread.h>
MODULE_LICENSE("GPL");

模块加载函数定义:

static int __init current_thread_info_init(void)
{
    printk("into current_thread_info_init.\n");
    printk("the current pid is:%d\n", current->pid);      //显示当前进程的进程号
    struct thread_info * info=current_thread_info( );    //获取当前进程的基本信息
    struct task_struct * task=info->task;                //获取当前进程的描述符信息
    printk("the pid of the thread is:%d\n", task->pid); //显示进程的PID
    printk("the tgid of the thread is:%d\n", task->tgid); //显示进程的TGID
    printk("the low level flags is:%u\n", info->flags); //显示进程的字段flags值
    printk("the thread synchronous flags is:%u\n", info->status); //显示进程的状态
    printk("current CPU is:%u\n", info->cpu);             //显示进程所在CPU编号
    printk("the preempt_count is:%d\n", info->saved_preempt_count);
                                                          // 显示进程的抢占计数器值
    printk("out current_thread_info_init.\n");
    return 0;
}

模块退出函数定义:

static void __exit current_thread_info_exit(void)
{
    printk("Goodbye current_thread_info\n");
}

模块加载、退出函数调用:

module_init(current_thread_info_init);
module_exit(current_thread_info_exit);

实例运行结果及分析:

首先编译模块,执行命令insmod current_thread_info.ko插入模块,然后执行命令dmesg -c查看系统输出信息,会出现如图所示的结果。

Linux内核 current_thread_info()

结果分析:

由上图可以看出变量current字段pid的值和函数current_thread_info( )返回的结构体中字段task字段的pid、tgid值相同,其实current和字段task是出于内核栈的同一个位置,current变量的值是内核自动完成的赋值的,对用户是透明的,可以看出当前进程在CPU0上运行,当前进程的抢占计数器是-2145396496,说明此进程允许被抢占。上图的输出信息说明函数current_thread_info( )能够获取当前进程的部分信息。

酷客网相关文章:

赞(0)

评论 抢沙发

评论前必须登录!