Printing stack traces

后端 未结 2 1959
谎友^
谎友^ 2021-01-20 02:04

I have a very short test file:

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

let f () = print_back         


        
2条回答
  •  情书的邮戳
    2021-01-20 02:13

    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 ()
    

    Here is a test run.

    $ /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.

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

    Best regards,

提交回复
热议问题