ºìÁªLinuxÃÅ»§
Linux°ïÖú

linuxÏÂ×·×Ùº¯Êýµ÷ÓöÑÕ»

·¢²¼Ê±¼ä:2008-06-11 21:19:33À´Ô´:ºìÁª×÷Õß:Archive
Ò»°ã²ì¿´º¯ÊýÔËÐÐʱ¶ÑÕ»µÄ·½·¨ÊÇʹÓÃGDBÖ®ÀàµÄÍⲿµ÷ÊÔÆ÷,µ«ÊÇ,ÓÐЩʱºòΪÁË·ÖÎö³ÌÐòµÄBUG,(Ö÷ÒªÕë¶Ô³¤Ê±¼äÔËÐгÌÐòµÄ·ÖÎö),ÔÚ³ÌÐò³ö´íʱ´òÓ¡³öº¯ÊýµÄµ÷ÓöÑÕ»ÊǷdz£ÓÐÓõġ£

ÔÚÍ·Îļþ"execinfo.h"ÖÐÉùÃ÷ÁËÈý¸öº¯ÊýÓÃÓÚ»ñÈ¡µ±Ç°Ï̵߳ĺ¯Êýµ÷ÓöÑÕ»

Function: int backtrace(void **buffer,int size)

¸Ãº¯ÊýÓÃÓë»ñÈ¡µ±Ç°Ï̵߳ĵ÷ÓöÑÕ»,»ñÈ¡µÄÐÅÏ¢½«»á±»´æ·ÅÔÚbufferÖÐ,ËüÊÇÒ»¸öÖ¸ÕëÁÐ±í¡£²ÎÊý size ÓÃÀ´Ö¸¶¨bufferÖпÉÒÔ±£´æ¶àÉÙ¸övoid* ÔªËØ¡£º¯Êý·µ»ØÖµÊÇʵ¼Ê»ñÈ¡µÄÖ¸Õë¸öÊý,×î´ó²»³¬¹ýsize´óС

ÔÚbufferÖеÄÖ¸Õëʵ¼ÊÊÇ´Ó¶ÑÕ»ÖлñÈ¡µÄ·µ»ØµØÖ·,ÿһ¸ö¶ÑÕ»¿ò¼ÜÓÐÒ»¸ö·µ»ØµØÖ·

×¢ÒâijЩ±àÒëÆ÷µÄÓÅ»¯Ñ¡Ïî¶Ô»ñÈ¡ÕýÈ·µÄµ÷ÓöÑÕ»ÓиÉÈÅ,ÁíÍâÄÚÁªº¯ÊýûÓжÑÕ»¿ò¼Ü;ɾ³ý¿ò¼ÜÖ¸ÕëÒ²»áʹÎÞ·¨ÕýÈ·½âÎö¶ÑÕ»ÄÚÈÝ

Function: char ** backtrace_symbols (void *const *buffer, int size)

backtrace_symbols½«´Óbacktraceº¯Êý»ñÈ¡µÄÐÅϢת»¯ÎªÒ»¸ö×Ö·û´®Êý×é. ²ÎÊýbufferÓ¦¸ÃÊÇ´Óbacktraceº¯Êý»ñÈ¡µÄÊý×éÖ¸Õë,sizeÊǸÃÊý×éÖеÄÔªËظöÊý(backtraceµÄ·µ»ØÖµ)

º¯Êý·µ»ØÖµÊÇÒ»¸öÖ¸Ïò×Ö·û´®Êý×éµÄÖ¸Õë,ËüµÄ´óСͬbufferÏàͬ.ÿ¸ö×Ö·û´®°üº¬ÁËÒ»¸öÏà¶ÔÓÚbufferÖжÔÓ¦ÔªËصĿɴòÓ¡ÐÅÏ¢.Ëü°üÀ¨º¯ÊýÃû£¬º¯ÊýµÄÆ«ÒƵØÖ·,ºÍʵ¼ÊµÄ·µ»ØµØÖ·

ÏÖÔÚ,Ö»ÓÐʹÓÃELF¶þ½øÖƸñʽµÄ³ÌÐòºÍ¿àÖÔ²ÅÄÜ»ñÈ¡º¯ÊýÃû³ÆºÍÆ«ÒƵØÖ·.ÔÚÆäËûϵͳ,Ö»ÓÐ16½øÖƵķµ»ØµØÖ·Äܱ»»ñÈ¡.ÁíÍâ,Äã¿ÉÄÜÐèÒª´«µÝÏàÓ¦µÄ±êÖ¾¸øÁ´½ÓÆ÷,ÒÔÄÜÖ§³Öº¯ÊýÃû¹¦ÄÜ(±ÈÈç,ÔÚʹÓÃGNU ldµÄϵͳÖÐ,ÄãÐèÒª´«µÝ(-rdynamic))

¸Ãº¯ÊýµÄ·µ»ØÖµÊÇͨ¹ýmallocº¯ÊýÉêÇëµÄ¿Õ¼ä,Òò´Ëµ÷ÓÃÕâ±ØÐëʹÓÃfreeº¯ÊýÀ´ÊÍ·ÅÖ¸Õë.

×¢Òâ:Èç¹û²»ÄÜΪ×Ö·û´®»ñÈ¡×ã¹»µÄ¿Õ¼äº¯ÊýµÄ·µ»ØÖµ½«»áΪNULL

Function:void backtrace_symbols_fd (void *const *buffer, int size, int fd)

backtrace_symbols_fdÓëbacktrace_symbols º¯Êý¾ßÓÐÏàͬµÄ¹¦ÄÜ,²»Í¬µÄÊÇËü²»»á¸øµ÷ÓÃÕß·µ»Ø×Ö·û´®Êý×é,¶øÊǽ«½á¹ûдÈëÎļþÃèÊö·ûΪfdµÄÎļþÖÐ,ÿ¸öº¯Êý¶ÔÓ¦Ò»ÐÐ.Ëü²»ÐèÒªµ÷ÓÃmallocº¯Êý,Òò´ËÊÊÓÃÓÚÓпÉÄܵ÷Óøú¯Êý»áʧ°ÜµÄÇé¿ö

ÏÂÃæµÄÀý×ÓÏÔʾÁËÕâÈý¸öº¯ÊýµÄÓ÷¨

ÒýÓÃ:
#include
#include
#include

/* Obtain a backtrace and print it to stdout. */
void
print_trace (void)
{
void *array[10];
size_t size;
char **strings;
size_t i;

size = backtrace (array, 10);
strings = backtrace_symbols (array, size);

printf ("Obtained %zd stack frames.\n", size);

for (i = 0; i < size; i++)
printf ("%s\n", strings[i]);

free (strings);
}

/* A dummy function to make the backtrace more interesting. */
void
dummy_function (void)
{
print_trace ();
}

int
main (void)
{
dummy_function ();
return 0;
}


±¸×¢:void *const *buffer -- bufferÖ¸ÏòcharÀàÐ͵ij£Á¿Ö¸ÕëµÄÖ¸Õë(ºÜÊÇÞÖ¿Ú)
ÎÄÕÂÆÀÂÛ

¹²ÓÐ 0 ÌõÆÀÂÛ