Linux内核模块中printk的奇怪行为 [英] Strange behavior of printk in linux kernel module

查看:179
本文介绍了Linux内核模块中printk的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为linux内核模块编写代码,并且在其中遇到奇怪的行为. 这是我的代码:

I am writing a code for linux kernel module and experiencing a strange behavior in it. Here is my code:

int data = 0;
void threadfn1()
{
    int j;
    for( j = 0; j < 10; j++ )
        printk(KERN_INFO "I AM THREAD 1 %d\n",j);   
    data++;
}

void threadfn2()
{
    int j;
    for( j = 0; j < 10; j++ )
        printk(KERN_INFO "I AM THREAD 2 %d\n",j);
    data++; 
}
static int __init abc_init(void)
{
        struct task_struct *t1 = kthread_run(threadfn1, NULL, "thread1");
        struct task_struct *t2 = kthread_run(threadfn2, NULL, "thread2");
        while( 1 )
        {
        printk("debug\n"); // runs ok
            if( data >= 2 )
            {
                kthread_stop(t1);
                kthread_stop(t2);
                break;
            }
        }
        printk(KERN_INFO "HELLO WORLD\n");

 }

基本上,我试图等待线程完成,然后再打印一些内容. 上面的代码确实实现了该目标,但未注释WITH "printk("debug\n");".一旦我注释掉printk("debug\n");以便在不调试的情况下运行代码并通过insmod命令加载模块,模块就会挂起,并且似乎在递归中丢失了.我不为什么printk会以如此大的方式影响我的代码?

Basically I was trying to wait for threads to finish and then print something after that. The above code does achieve that target but WITH "printk("debug\n");" not commented. As soon as I comment out printk("debug\n"); to run the code without debugging and load the module through insmod command, the module hangs on and it seems like it gets lost in recursion. I dont why printk effects my code in such a big way?

任何帮助将不胜感激.

致谢.

推荐答案

删除对printk()的调用后,编译器正在优化进入while (1);的循环.当您将调用添加到printk()时,编译器不确定data未被更改,因此每次通过循环检查该值.

With the call to printk() removed the compiler is optimising the loop into while (1);. When you add the call to printk() the compiler is not sure that data isn't changed and so checks the value each time through the loop.

您可以在循环中插入一个障碍,这会迫使编译器在每次迭代时重新评估data.例如:

You can insert a barrier into the loop, which forces the compiler to reevaluate data on each iteration. eg:

while (1) {
        if (data >= 2) {
                kthread_stop(t1);
                kthread_stop(t2);
                break;
        }

        barrier();
}

这篇关于Linux内核模块中printk的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆