Linux Kernel Source - __FILE__ __LINE__ 妙用

在Linux 2.4内核代码wait.h,看到如下定义

               #define WQ_BUG()    BUG()

其中BUG()是在page.h中定义的,定义如下:

               #define BUG() do { printk("kernel BUG at %s:%d!\n", __FILE__, __LINE__); *(int *)0=0; } while (0)

看到这句,我就纳闷了printk打印出错的文件名和行号,那么*(int *)0=0;是做什么用的呢?写一个小程序你就知道了:

dance@dance-desktop:~/testc/bug$ cat bug.c 
#include <stdio.h>
int main(void)
{
    //printf("kernel BUG at %s:%d!\n", __FILE__, __LINE__);
    *(int *)0=0;
    return 0;
}
dance@dance-desktop:~/testc/bug$ gcc bug.c 
dance@dance-desktop:~/testc/bug$ ./a.out 
Segmentation fault
dance@dance-desktop:~/testc/bug$ 

看到上面的demo相信你已经知道了*(int *)0=0;会产生Segmentation fault错误,事实上任何向(int *)0进行写操作都会产生Segmentation fault错误。

此时我们将printf哪行的注释去掉,演示如下:

dance@dance-desktop:~/testc/bug$ cat bug.c 
#include <stdio.h>
int main(void)
{
    printf("kernel BUG at %s:%d!\n", __FILE__, __LINE__);
    *(int *)0=0;
    return 0;
}
dance@dance-desktop:~/testc/bug$ gcc bug.c 
dance@dance-desktop:~/testc/bug$ ./a.out 
kernel BUG at bug.c:4!            //打印出了出错文件名和行号         
Segmentation fault
dance@dance-desktop:~/testc/bug$ 
总结:

当我们遇到需要打印调试信息的时候__FILE__ __LINE__和文章开头定义的两个宏是不错的选则,例如在遇到空指针时:

Linux 2.4 wait.h
static inline void init_waitqueue_head(wait_queue_head_t *q)
{
#if WAITQUEUE_DEBUG
	if (!q)                    // Notice Here
		WQ_BUG();
#endif
	q->lock = WAITQUEUE_RW_LOCK_UNLOCKED;
	INIT_LIST_HEAD(&q->task_list);
#if WAITQUEUE_DEBUG
	q->__magic = (long)&q->__magic;
	q->__creator = (long)current_text_addr();
#endif
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值