2009-06-10 15 views
5

特定のポイントでCアプリケーションのスタック情報を取得する必要があります。私はドキュメントを読んでネットを検索しましたが、どうやってそれをやり遂げることができないのか分かりません。あなたは簡単なプロセスの説明を指すことができますか?あるいは、スタックの巻き戻しの例に、より良い。私はHP-UX(Itanium)とLinuxに必要です。HP-UXとLinuxでのスタック解凍

答えて

4

ここ

は、APIリファレンスであるのlinux/stacktrace.hをチェックアウト:

http://www.cs.cmu.edu/afs/cs/Web/People/tekkotsu/dox/StackTrace_8h.html

はここ

すべてのLinuxカーネルで動作するはずですがからCに代替例であります

http://www.linuxjournal.com/article/6391

#include <stdio.h> 
#include <signal.h> 
#include <execinfo.h> 

void show_stackframe() { 
    void *trace[16]; 
    char **messages = (char **)NULL; 
    int i, trace_size = 0; 

    trace_size = backtrace(trace, 16); 
    messages = backtrace_symbols(trace, trace_size); 
    printf("[bt] Execution path:\n"); 
    for (i=0; i<trace_size; ++i) 
    printf("[bt] %s\n", messages[i]); 
} 


int func_low(int p1, int p2) { 

    p1 = p1 - p2; 
    show_stackframe(); 

    return 2*p1; 
} 

int func_high(int p1, int p2) { 

    p1 = p1 + p2; 
    show_stackframe(); 

    return 2*p1; 
} 


int test(int p1) { 
    int res; 

    if (p1<10) 
    res = 5+func_low(p1, 2*p1); 
    else 
    res = 5+func_high(p1, 2*p1); 
    return res; 
} 



int main() { 

    printf("First call: %d\n\n", test(27)); 
    printf("Second call: %d\n", test(4)); 

} 
+0

APIが存在することはわかりませんでした。どのように便利です! – Jamie

+0

HP-UX用には役に立ちません。 – DaveR

+0

@dave、nit-picker:P –

3

あなたはlibunwind見たい - これは(特に複雑です)Itaniumのスタックトレースを巻き戻すためにHPが独自に開発したクロスプラットフォームのライブラリです。その後他の多くのプラットフォームにも拡張されました。 x86-LinuxとItanium-HPUXの両方が含まれます。

libunwind(3)のマニュアルページから、ここでは典型的な 'ショーのバックトレース' 関数を書くことlibunwindの使用例です:

#define UNW_LOCAL_ONLY 
#include <libunwind.h> 

void show_backtrace (void) { 
    unw_cursor_t cursor; unw_context_t uc; 
    unw_word_t ip, sp; 

    unw_getcontext(&uc); 
    unw_init_local(&cursor, &uc); 
    while (unw_step(&cursor) > 0) { 
    unw_get_reg(&cursor, UNW_REG_IP, &ip); 
    unw_get_reg(&cursor, UNW_REG_SP, &sp); 
    printf ("ip = %lx, sp = %lx\n", (long) ip, (long) sp); 
    } 
}