0x90
0x90

Reputation: 40982

Why does my kernel thread execute only once?

following this post I have implemented in my kernel module:

static int val = 1;
static char thread_name[128] = "my thread name";

in the init:

thread1 = kthread_run(thread_fn, &val, thread_name);

and this is the function

int thread_fn(void *data)
{
    unsigned long j0,j1;
    int delay = 60*HZ;
    j0 = jiffies; 
    j1 = j0 + delay; 

    printk(KERN_INFO "here");

    while (time_before(jiffies, j1)) 
        schedule();
    return 1;
}

Why does this execute only 1 time ?

Upvotes: 1

Views: 572

Answers (2)

sfstewman
sfstewman

Reputation: 5677

Based on the accepted answer to How to stop Linux kernel threads on rmmod?, and some of my own poking around, I suspect that there are two possible causes:

  1. Your function returns.

  2. Your thread state is TASK_INTERRUPTIBLE, so a call to schedule() will never return.

If you wrap the body in a while (! kthread_should_stop() ) loop, and make sure that your task is in a TASK_RUNNING state before a call to schedule(), then it will keep running:

int thread_fn(void *data)
{
    unsigned long j1;
    int delay = 5*HZ;  /* use a 5-second delay instead of a 60-sec one */

    int count = 0;
    while (! kthread_should_stop() ) {
        j1 = jiffies + delay; 

        printk(KERN_INFO "here %d\n", ++count);

        while (time_before(jiffies, j1)) {
            set_current_state(TASK_RUNNING);
            schedule();
        }
    }
    return 1;
}

Upvotes: 1

krase
krase

Reputation: 1044

This is the normal behavior of any thread. If you want a cyclical behaviour, you need a loop in thread_fn.
Here is a nice documentation for kernel threads: https://prof.hti.bfh.ch/myf1/adv-linux/courseNotes/kthread-intro-1.2.pdf

Upvotes: 1

Related Questions