set_user_nice
set_user_nice
函数功能:设置某一进程的NICE值,其NICE值的计算是根据进程的静态优先级(task_struct->static_prio),直接通过set_user_nice函数更改进程的静态优先级。
内核源码
void set_user_nice(struct task_struct *p, long nice)
{bool queued, running;int old_prio;struct rq_flags rf;struct rq *rq;if (task_nice(p) == nice || nice < MIN_NICE || nice > MAX_NICE)return;/** We have to be careful, if called from sys_setpriority(),* the task might be in the middle of scheduling on another CPU.*/rq = task_rq_lock(p, &rf);update_rq_clock(rq);/** The RT priorities are set via sched_setscheduler(), but we still* allow the 'normal' nice value to be set - but as expected* it wont have any effect on scheduling until the task is* SCHED_DEADLINE, SCHED_FIFO or SCHED_RR:*/if (task_has_dl_policy(p) || task_has_rt_policy(p)) {p->static_prio = NICE_TO_PRIO(nice);goto out_unlock;}queued = task_on_rq_queued(p);running = task_current(rq, p);if (queued)dequeue_task(rq, p, DEQUEUE_SAVE | DEQUEUE_NOCLOCK);if (running)put_prev_task(rq, p);p->static_prio = NICE_TO_PRIO(nice);set_load_weight(p, true);old_prio = p->prio;p->prio = effective_prio(p);if (queued)enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);if (running)set_next_task(rq, p);/** If the task increased its priority or is running and* lowered its priority, then reschedule its CPU:*/p->sched_class->prio_changed(rq, p, old_prio);out_unlock:task_rq_unlock(rq, p, &rf);
}
EXPORT_SYMBOL(set_user_nice);
使用示例
#include <linux/module.h>
#include <linux/pid.h>
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/kthread.h>static int MyThreadFunc(void* argc) {printk("Prompt:kernel thread PID : %d.\n", current->pid);printk("Prompt:kernel thread static_prio : %d.\n", current->static_prio);printk("Prompt:kernel thread nice : %d.\n", task_nice(current));return 0;
}static int __init SetUserNiceInit(void) {struct task_struct* new_task = NULL;new_task = kthread_create_on_node(MyThreadFunc, NULL, -1, "setusernice.c");printk("Prompt:new thread nice : %d.\n", task_nice(new_task));printk("Prompt:new thread static_prio : %d.\n", new_task->static_prio);printk("Prompt:new thread prio : %d.\n", new_task->prio);set_user_nice(new_task, 16);printk("Prompt:new thread nice : %d.\n", task_nice(new_task));printk("Prompt:new thread static_prio : %d.\n", new_task->static_prio);printk("Prompt:new thread prio : %d.\n", new_task->prio);return 0;
}static void __exit SetUserNiceExit(void) {printk("Prompt:exit kernel.\n");
}module_init(SetUserNiceInit);
module_exit(SetUserNiceExit);