作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我写了下面的代码来创建一个内核线程:
#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).
*/
我认为终止线程的两种选择是:
do_exit()
。kthread_stop()
时返回一个值。希望在解决这两个小问题后,您将拥有一个功能强大的线程创建器/收割器。
关于c - 如何在 rmmod 上停止 Linux 内核线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5280693/
我是一名优秀的程序员,十分优秀!