Linux内核 task_nice()

函数:task_nice( )

文件包含:

        #include <linux/sched.h>

函数定义:

在内核源码中的位置:linux-3.19.3/include/linux/sched.h

函数定义格式:

static inline int task_nice(const struct task_struct *p)
{
    return PRIO_TO_NICE((p)->static_prio);
}

函数功能描述:

此函数用于获取进程的nice值,nice值其实代表进程的优先级,此优先级与静态优先级有关,与静态优先级的关系是:nice=static_prio-120

输入参数说明:

此函数的第一个参数是进程描述符信息,其定义比较复杂,在内核注释中关于此参数说明比较详细,具体定义请参见内核源码文件linux-3.19.3/include/linux/sched.h。

返回参数说明:

此函数返回的值是int型的变量,代表当前进程的nice值,其取值范围是-20~19, nice值越小,代表其优先级越大。

实例解析:

编写测试文件:task_nice.c

头文件引用:

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

子进程函数定义:

int my_function(void * argc)
{
    printk("in the kernel thread function! \n");
    printk("the current static_prio is:%d\n", current->static_prio);
                                                              // 显示当前进程的静态优先级
    printk("the current nice is:%d\n", task_nice(current)); //显示当前进程的nice值
    printk("the current pid is:%d\n", current->pid);          //显示当前进程的PID值
    printk("out the kernel thread function\n");
    return 0;
}

模块加载函数定义:

static int __init task_nice_init(void)
{
    struct task_struct * result;
    int priority;
    printk("into task_nice_init.\n");
    result=kthread_create_on_node(my_function, NULL, -1, "task_nice"); //创建新进程
    wake_up_process(result);

    priority=task_nice(result);   //获取新进程的nice值
    printk("the static_prio of the child thread is:%d\n", result->static_prio);
                                  // 显示新进程的静态优先级
    printk("the nice of the child thread is:%d\n", priority); //显示新进程的nice值
    printk("the pid of new thread is :%d\n", result->pid);
                                  //显示函数kernel_thread( )的返回结果
    printk("the current static_prio is:%d\n", current->static_prio);
                                  // 显示当前进程的静态优先级
    printk("the current pid is:%d\n", current->pid);           //显示当前进程的PID值
    printk("the current nice is:%d\n", task_nice(current));    //显示当前进程的nice值
    printk("out task_nice_init.\n");
    return 0;
}

模块退出函数定义:

static void __exit task_nice_exit(void)
{
    printk("Goodbye task_nice\n");
}

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

module_init(task_nice_init);
module_exit(task_nice_exit);

实例运行结果及分析:

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

Linux内核 task_nice()

结果分析:

由上图可以看出,刚创建的新进程其静态优先级是120,其nice值为0,对于父进程其静态优先级也是120, nice值也是0。函数task_nice( )能够获得进程的nice值,nice值的获取也是根据进程的静态优先级计算出来的,他们之间有固定的关系。

酷客网相关文章:

赞(0)

评论 抢沙发

评论前必须登录!