Linux Kernel Process NICE Analysis and Implementation

set_user_nice Function

The set_user_nice functon modifies the NICE value of a specified process, wich adjusts its static priority (task_struct->static_prio). This change directly influences the process's scheduling behavior.

Kerneel Source Code

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;

    rq = task_rq_lock(p, &rf);
    update_rq_clock(rq);

    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);

    p->sched_class->prio_changed(rq, p, old_prio);

out_unlock:
    task_rq_unlock(rq, p, &rf);
}
EXPORT_SYMBOL(set_user_nice);

Example Implementation

#include <linux/module.h>
#include <linux/pid.h>
#include <linux/sched.h>
#include <linux/kthread.h>

static int custom_thread_function(void* arg) {
    printk("Thread PID: %d\n", current->pid);
    printk("Thread static_prio: %d\n", current->static_prio);
    printk("Thread nice value: %d\n", task_nice(current));
    return 0;
}

static int __init example_module_init(void) {
    struct task_struct* new_thread = NULL;

    new_thread = kthread_create_on_node(custom_thread_function, NULL, -1, "nice_example");

    printk("Initial nice value: %d\n", task_nice(new_thread));
    printk("Initial static_prio: %d\n", new_thread->static_prio);
    printk("Initial prio: %d\n", new_thread->prio);

    set_user_nice(new_thread, 16);

    printk("Updated nice value: %d\n", task_nice(new_thread));
    printk("Updated static_prio: %d\n", new_thread->static_prio);
    printk("Updated prio: %d\n", new_thread->prio);

    return 0;
}

static void __exit example_module_exit(void) {
    printk("Module unloading\n");
}

module_init(example_module_init);
module_exit(example_module_exit);

Tags: linux-kernel process-scheduling static-priority nice-value task-struct

Posted on Mon, 13 Jul 2026 16:35:53 +0000 by nerya