6.5. 我能在一个运行着的程序中生成堆栈映象吗?

一些系统提供库函数可以提取(unwinding)出堆栈,从而(比如)你可以在一个错误 处理函数中生成一个堆栈映象,但是只有一小部分系统有这些函数。

一个可能的变通方法(workaround)是让你的程序执行一个调试器调试*它自己* - 详细方法仍然根据不同系统稍有不同,但一般的概念是这样:

     void dump_stack(void)
     {
         char s[160];

         sprintf(s, "/bin/echo 'where\ndetach' | dbx -a %d", getpid());
         system(s);

         return;
     }
    

你需要根据你不同的系统对dbx的参数和命令进行加工,或者甚至换另一个调试 器,比如‘gdb’,但这仍然是我见过的对于这种问题最普遍的解决方法。为此, 荣誉授予Ralph Corderoy。

下面列表包含在一些系统上需要用到的命令行:

大多数使用dbx的系统
    `"/bin/echo 'where\ndetach' | dbx /path/to/program %d"'

AIX
     `"/bin/echo 'where\ndetach' | dbx -a %d"'

IRIX
     `"/bin/echo 'where\ndetach' | dbx -p %d"'