gpt4 book ai didi

c - 如何在 rmmod 上停止 Linux 内核线程?

转载 作者:太空狗 更新时间:2023-10-29 16:25:42 29 4
gpt4 key购买 nike

我写了下面的代码来创建一个内核线程:

#include<linux/init.h>
#include<linux/module.h>
#include<linux/kernel.h>
#include<linux/kthread.h>
#include<linux/sched.h>

struct task_struct *task;
int data;
int ret;
int thread_function(void *data)
{
int var;
var = 10;
return var;
}

static int kernel_init(void)
{
data = 20;
printk(KERN_INFO"--------------------------------------------");
task = kthread_create(&thread_function,(void *)data,"pradeep");
task = kthread_run(&thread_function,(void *)data,"pradeep");
printk(KERN_INFO"Kernel Thread : %s\n",task->comm);
return 0;
}

static void kernel_exit(void)
{
ret = kthread_stop(task);
}

module_init(kernel_init);
module_exit(kernel_exit);

在给出 insmod 命令时,我能够创建一个名为“pradeep”的内核线程,并且我可以使用ps -ef命令如下

root      6071     2  0 10:21 ?        00:00:00 [pradeep]

它的父线程是 kthreadd,它的 PID 是 2。但是我无法在发出 rmmod 命令时停止此线程。它给出以下输出:

ERROR: Removing 'pradeep': Device or resource busy.

有人可以告诉我如何终止这个线程吗?

最佳答案

您应该只使用kthread_create()kthread_run() 之一:

/**
* kthread_run - create and wake a thread.
* @threadfn: the function to run until signal_pending(current).
* @data: data ptr for @threadfn.
* @namefmt: printf-style name for the thread.
*
* Description: Convenient wrapper for kthread_create() followed by
* wake_up_process(). Returns the kthread or ERR_PTR(-ENOMEM).
*/
#define kthread_run(threadfn, data, namefmt, ...) \
({ \
struct task_struct *__k \
= kthread_create(threadfn, data, namefmt, ## __VA_ARGS__); \
if (!IS_ERR(__k)) \
wake_up_process(__k); \
__k; \
})

因此您正在创建两个 线程并泄漏其中一个:

task = kthread_create(&thread_function,(void*) &data,"pradeep");
task = kthread_run(&thread_function,(void*) &data,"pradeep");

此外,您的线程函数可能缺少一些细节:

/**
* kthread_create - create a kthread.
* @threadfn: the function to run until signal_pending(current).
* @data: data ptr for @threadfn.
* @namefmt: printf-style name for the thread.
*
* Description: This helper function creates and names a kernel
* thread. The thread will be stopped: use wake_up_process() to start
* it. See also kthread_run().
*
* When woken, the thread will run @threadfn() with @data as its
* argument. @threadfn() can either call do_exit() directly if it is a
* standalone thread for which noone will call kthread_stop(), or
* return when 'kthread_should_stop()' is true (which means
* kthread_stop() has been called). The return value should be zero
* or a negative error number; it will be passed to kthread_stop().
*
* Returns a task_struct or ERR_PTR(-ENOMEM).
*/

我认为终止线程的两种选择是:

  1. 完成后调用 do_exit()
  2. 当另一个线程调用kthread_stop()时返回一个值。

希望在解决这两个小问题后,您将拥有一个功能强大的线程创建器/收割器。

关于c - 如何在 rmmod 上停止 Linux 内核线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5280693/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com