运行两个内核线程。怎么实现呢?

时间:2014-03-20 14:28:15

标签: c multithreading linux-kernel kernel-module

我编写了一个运行两个线程的内核模块。但它一直在崩溃。我认为init函数似乎有问题。这是init函数

 int __init ksocket_init(void)
 {
    kthread = kmalloc(sizeof(struct kthread_t), GFP_KERNEL);
    memset(kthread, 0, sizeof(struct kthread_t));

    /* start kernel thread */
    kthread->thread = kthread_run((void *)ksocket_start, NULL, MODULE_NAME);
    kthread_server->thread = kthread_run((void *)ksocket_start_server, NULL, MODULE_NAME);

    if (IS_ERR(kthread->thread) || IS_ERR(kthread_server->thread)) {
            printk(KERN_INFO MODULE_NAME": unable to start kernel thread\n");

            kfree(kthread);
            kthread = NULL;

            kfree(kthread_server);
            kthread = NULL;

            return -ENOMEM;
    }

    return 0;
}

它有什么问题吗?我熟悉应用程序级的多线程。但是,我没有足够的内核线程知识。任何帮助表示赞赏。

答案:

我使用的是未分配的kthread_server变量。

新问题:

但是,现在我无法卸载模块。这是退出功能。

void __exit ksocket_exit(void)
{
int err;
struct mutex mutex_ks;

mutex_init(&mutex_ks);
if (kthread->thread==NULL)
        printk(KERN_INFO MODULE_NAME": no kernel thread to kill\n");
else
{
        mutex_lock(&mutex_ks);
        err = kthread_stop(kthread->thread);
        mutex_unlock(&mutex_ks);

        /* wait for kernel thread to die */
        if (err < 0)
                printk(KERN_INFO MODULE_NAME": unknown error %d while trying to terminate kernel thread\n",-err);
        else
        {
                while (kthread->running == 1)
                        msleep_interruptible(10);
                printk(KERN_INFO MODULE_NAME": succesfully killed kernel thread!\n");
        }
}

/* free allocated resources before exit */
if (kthread->sock_local != NULL)
{
        sock_release(kthread->sock_local);
        kthread->sock_local = NULL;
}

kfree(kthread);
kthread = NULL;

if (kthread_server->thread==NULL)
        printk(KERN_INFO MODULE_NAME": no kernel thread to kill\n");
else
{
            mutex_lock(&mutex_ks);
        err = kthread_stop(kthread_server->thread);
        mutex_unlock(&mutex_ks);

        /* wait for kernel thread to die */
        if (err < 0)
                printk(KERN_INFO MODULE_NAME": unknown error %d while trying to terminate kernel thread\n",-err);
        else
        {
                while (kthread_server->running == 1)
                        msleep_interruptible(10);
                printk(KERN_INFO MODULE_NAME": succesfully killed kernel thread!\n");
        }
}

/* free allocated resources before exit */
if (kthread_server->sock != NULL)
{
        sock_release(kthread_server->sock);
        kthread_server->sock = NULL;
}

kfree(kthread_server);
kthread_server = NULL;

printk(KERN_INFO MODULE_NAME": module unloaded\n");
}

有人能解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

您正在kthread_server下使用未分配的内存。分配为kthread变量。