How to kill a wait queue in kernel module?

2019-07-25 07:03发布

问题:

I am new to kernel module. Using a wait queue, I am blocking the thread until the buffer has data. Using hrtimer, I am periodically waking up the queue. Now, the problem is even after I remove the kernel module, I could see that the process "thread1" is still running. I think the issue is that the wait queue is waiting forever and the process got blocked here. Please help me how can I kill the wait queue when I remove my module.

void thread1(void)
{
    while (thread_running) {
        ...
        wait_event_interruptible(wait_queue, does_buffer_have_data());
        ...
    }
}

回答1:

Common way for wait within kernel thread:

void thread1(void)
{
    while(!kthread_should_stop())
    {
        ...
        wait_event_interruptible(wait_queue,
             does_buffer_have_data() || kthread_should_stop());
        if(kthread_should_stop()) break;
        ...
    }
}

void module_cleanup(void)
{
    kthread_stop(t);
}

Function kthread_should_stop checks stop flag for current thread.

Function kthread_stop(t) sets stop flag for thread t, interrupt any waiting performed by this thread, and waits while the thread is finished.


Note, that while kthread_stop interrupts waiting, it doesn't set any pending signal for the thread.

Because of that interruptible wait for event (wait_event_interruptible and so) doesn't return -EINTR just after kthread_stop but only rechecks condition.

So, if waiting for event wants to be returned after kthread_stop, it should check stop flag explicitely in condition.