Skip to content
systemcoding.dev
Kernels

Start a kernel thread with kthread_run

Create and wake a kernel thread in one call with kthread_run(), check the ERR_PTR return, and give it a name that shows up in ps on Linux 6.x.

1 min read
Summarize in AI

A driver that needs a background loop starts a kernel thread. kthread_run() is a macro in linux/kthread.h that calls kthread_create() and then wake_up_process(), so the thread begins running at once. It takes a printf-style name, which is what ps and top show in brackets.

c
#include <linux/module.h>
#include <linux/kthread.h>

static struct task_struct *worker;

static int worker_fn(void *data)
{
	pr_info("demo: running as pid %d (%s)\n", current->pid, current->comm);
	return 0;
}

static int __init demo_init(void)
{
	worker = kthread_run(worker_fn, NULL, "demo-worker/%d", 0);
	if (IS_ERR(worker))
		return PTR_ERR(worker);
	return 0;
}
module_init(demo_init);
MODULE_LICENSE("GPL");
Text
demo: running as pid 3187 (demo-worker/0)

The failure path is the part to remember: kthread_run() never returns NULL. On error it returns an ERR_PTR, so test with IS_ERR(), as above, and not if (!worker). The PID differs on every run.

The thread here ends by returning from worker_fn, which is fine, but then you must not call kthread_stop() on the saved pointer unless you also hold a reference with get_task_struct(). A thread that loops until told to stop is the next snippet. Names longer than 15 characters are truncated in comm, per the kthread API.

Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.