如何正确创建和停止kthreads?

如何正确创建和停止kthreads?

我编写了以下内核模块:

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/kthread.h>
#include <linux/sched.h>
#include <linux/semaphore.h>
#include <linux/spinlock.h> 
     
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Madhuparna Bhowmik <[email protected]>");
MODULE_DESCRIPTION("Example for using threads");
    
static struct task_struct *t1;
static struct task_struct *t2;

static int t1_f(void *unused)
{
    printk(KERN_INFO "Current value in t1 is %d",7);
    do_exit(0);
    return 0;
}

static int t2_f(void *unused)
{
    printk(KERN_INFO "Current value in t2 is %d",8);
    do_exit(0);
    return 0;
}

static int __init start_init(void)
{
    printk(KERN_INFO "Thread Creating...\n");
    t1 = kthread_run(t1_f,NULL,"mythread1");
    t2 = kthread_run(t2_f,NULL,"mythread2");
    
    return 0;
}

static void __exit end_exit(void)
{
    printk(KERN_INFO "Cleaning Up...\n");
}

    
module_init(start_init)
module_exit(end_exit)

当我使用以下命令加载此模块时:

sudo insmod test1.ko

检查 kern.log 文件给出以下结果:

Oct  8 00:24:13 madhuparna-VirtualBox kernel: [ 5752.075918] Thread creating ...

Oct  8 00:24:13 madhuparna-VirtualBox kernel: [ 5752.076009] Current value in t1 is 7

线程 2 还没有日志。

我执行后:

sudo rmmod test1.ko

日志是:

Oct  8 00:24:13 madhuparna-VirtualBox kernel: [ 5752.075918] Thread creating ...
Oct  8 00:24:13 madhuparna-VirtualBox kernel: [ 5752.076009] Current value in t1 is 7
Oct  8 00:24:54 madhuparna-VirtualBox kernel: [ 5752.077780] Current value in t2 is 8
Oct  8 00:24:54 madhuparna-VirtualBox kernel: [ 5793.099359] Cleaning up ...

那么,有人可以解释一下为什么线程 2 在我使用 rmmod 并卸载内核之前才开始运行吗?为什么只有thread1在执行?

答案1

您需要在 的末尾附加一个换行符printk()。似乎printk()没有换行符不会被冲入,dmesg直到另一个printk()没有KERN_CONT

printk(KERN_INFO "Current value in t1 is %d\n",7);
printk(KERN_INFO "Current value in t2 is %d\n",8);

至于如何正确创建和停止kthreads,这里是我写的示例代码。希望它会有所帮助。 https://gist.github.com/seekstar/4bdef2a775383d417e265317832e44ed

使用原因struct completion enteredhttps://stackoverflow.com/questions/65987208/kthread-stopped-without-running

您可以通过以下方式取消线程:

t1 = kthread_create(func, &para1, "t1");
// Oops, something went wrong(such as failing to create another kthread)
ret = kthread_stop(t1);

这样,func就不会被执行,并且ktheard_stop会返回-EINTR

相关内容