本文介绍了打印堆叠痕迹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常短的测试文件:

I have a very short test file:

let print_backtrace () = try raise Not_found with
    Not_found -> Printexc.print_backtrace stdout;;

let f () = print_backtrace (); Printf.printf "this is to make f non-tail-recursive\n";;

f ();

我编译并运行:

% ocamlc -g test.ml
% OCAMLRUNPARAM=b ./a.out
Raised at file "test.ml", line 1, characters 35-44
this is to make f non-tail-recursive

为什么不是$ code > f 列出堆栈跟踪?我如何编写一个函数来打印它所调用的位置的堆栈跟踪?

Why isn't f listed in the stack trace? How can I write a function that will print a stack trace of the location it's called from?

推荐答案

这里是要执行的代码我建议什么我建议使用ocamldebug,如果可能的话,这段代码太棘手了。但是它可以在我的系统上为这个简单的例子。

Here is the code to do what I suggested. I recommend using ocamldebug if at all possible, this code is much too tricky. But it works on my system for this simple example.

let print_backtrace () =
    match Unix.fork () with
    | 0 -> raise Not_found
    | pid -> let _ = Unix.waitpid [] pid in ()

let f () =
    begin
    print_backtrace ();
    Printf.printf "after the backtrace\n";
    end

;;

f ()

这是一个测试运行。

$ /usr/local/ocaml312/bin/ocamlc unix.cma -g test3.ml
$ OCAMLRUNPARAM=b a.out
Fatal error: exception Not_found
Raised at file "test3.ml", line 3, characters 17-26
Called from file "test3.ml", line 8, characters 4-22
Called from file "test3.ml", line 14, characters 0-4
after the backtrace

我意识到,由于未被捕获的异常,您并没有真正控制子进程退出的方式。这是这个代码太棘手的原因之一。请不要责怪我,如果它不适合你,但我希望它证明是有用的。

I realized that because of the uncaught exception, you don't really have any control over the way the child process exits. That's one reason this code is much too tricky. Please don't blame me if it doesn't work for you, but I hope it does prove useful.

我在Mac OS X 10.6.8上测试了代码,使用OCaml 3.12.0。

I tested the code on Mac OS X 10.6.8 using OCaml 3.12.0.

祝福,

这篇关于打印堆叠痕迹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 06:18