Quantcast
Channel: Active questions tagged kernel-modules - Unix & Linux Stack Exchange
Viewing all articles
Browse latest Browse all 1186

How to correctly create and stop kthreads?

$
0
0

I wrote the following kernel module:

    #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 <madhuparnabhowmik04@gmail.com>");
    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)

When I load this module using :

sudo insmod test1.ko

Checking kern.log file gives the following result:

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

There is no log for thread2 yet.

After I execute :

sudo rmmod test1.ko

The log is:

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 ...

So, can someone please explain that why does thread 2 does not start running until I use rmmod and unload the kernel? Why is only thread1 executing?


Viewing all articles
Browse latest Browse all 1186

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>