捕获libc错误消息,从/ dev / tty

时间:2015-08-17 17:32:00

标签: c++ c libc

我正在尝试捕获libc在检测到错误情况时生成的错误消息。例如,我的测试代码:

#include <stdlib.h>

int main()
{
   char* p = (char*)malloc(10);
   free(p);
   free(p);
}

生成此输出

$ ./main
*** Error in `./main': double free or corruption (fasttop): 0x000000000124b010 ***
======= Backtrace: =========
/lib64/libc.so.6(+0x7d1fd)[0x7f8c121291fd]
./main[0x400b86]
/lib64/libc.so.6(__libc_start_main+0xf5)[0x7f8c120cdaf5]
./main[0x400a79]
... <snip>

但是,它不是写入stderr或stdout,而是/ dev / tty(我发现使用strace)

open("/dev/tty", O_RDWR|O_NOCTTY|O_NONBLOCK) = 3
writev(3, [{"*** Error in `", 14}, {"./main", 6}, {"': ", 3}, {"double free or corruption (fastt"..., 35}, {": 0x", 4}, {"00000000011bf010", 16}, {" ***\n", 5}], 7*** Error in `./main': double free or corruption (fasttop): 0x00000000011bf010 ***
) = 83
mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f0f2f7ac000
write(3, "======= Backtrace: =========\n", 29======= Backtrace: =========
) = 29
writev(3, [{"/lib64/libc.so.6", 16}, {"(", 1}, {"+0x", 3}, {"7d1fd", 5}, {")", 1}, {"[0x", 3}, {"7f0f2ea2a1fd", 12}, {"]\n", 2}], 8/lib64/libc.so.6(+0x7d1fd)[0x7f0f2ea2a1fd]
) = 43
writev(3, [{"./main", 6}, {"[0x", 3}, {"400b86", 6}, {"]\n", 2}], 4./main[0x400b86]
) = 17
writev(3, [{"/lib64/libc.so.6", 16}, {"(", 1}, {"__libc_start_main", 17}, {"+0x", 3}, {"f5", 2}, {")", 1}, {"[0x", 3}, {"7f0f2e9ceaf5", 12}, {"]\n", 2}], 9/lib64/libc.so.6(__libc_start_main+0xf5)[0x7f0f2e9ceaf5]
) = 57
writev(3, [{"./main", 6}, {"[0x", 3}, {"400a79", 6}, {"]\n", 2}], 4./main[0x400a79]
) = 17

如何将其重定向到文件?标准的stdout和stderr重定向不起作用。我需要捕获这个系统服务,现在,输出正在消失在以太中。

1 个答案:

答案 0 :(得分:12)

我通过检查libc source code, libc_fatal.c找到了一份未获发表的(不在glibc文档中!)答案。

将以下环境变量设置为任何

LIBC_FATAL_STDERR_=1

使libc写入stderr而不是/dev/tty