Untitled
unknown
plain_text
3 years ago
1.2 kB
7
Indexable
Aby utworzyć nowy wątek jądra Linux, należy skorzystać z interfejsu kernel_thread() z pliku nagłówkowego linux/kthread.h.
#include <linux/kthread.h>
#include <linux/sched.h>
static struct task_struct *thread_st;
int thread_fn(void *data)
{
// kod wykonywany przez wątek
while (!kthread_should_stop())
{
// instrukcje
set_current_state(TASK_INTERRUPTIBLE);
schedule();
}
return 0;
}
int init_module(void)
{
// Tworzenie nowego wątku
thread_st = kthread_run(thread_fn, NULL, "my_thread");
if (IS_ERR(thread_st))
{
printk(KERN_ERR "Nie udało się utworzyć wątku\n");
return PTR_ERR(thread_st);
}
return 0;
}
void cleanup_module(void)
{
// Zatrzymanie wątku
if (thread_st)
{
kthread_stop(thread_st);
printk(KERN_INFO "Wątek zatrzymany\n");
}
}
Powyższy kod tworzy nowy wątek jądra, który będzie wykonywał kod znajdujący się w funkcji thread_fn(). W tej funkcji należy umieścić instrukcje, które mają być wykonywane przez wątek. Wątek jest tworzony przy pomocy funkcji kthread_run() i jest zatrzymywany przy pomocy funkcji kthread_stop() w momencie wywołania funkcji cleanup_module()Editor is loading...