go - golang how to redirect panic in C code to a file -
it's easy redirect golang panic file, use recover() capture , use syscall.dup2() redirect. when comes c panic, seems useless, image, console show error message "fatal error: unexpected signal during runtime execution" , stack message. how redirect these error message file
package main /* #include <stdio.h> void sayhi(int a, int b) { int c = a/b; } */ import "c" import ( "runtime/debug" "syscall" "os" "log" ) func main() { logfile, logerr := os.openfile("/home/error.log", os.o_create|os.o_rdwr|os.o_append, 0666) if logerr != nil { log.println("fail find", *logfile) os.exit(1) } log.setoutput(logfile) defer func() { if r := recover(); r != nil { syscall.dup2(int(logfile.fd()), 2) debug.printstack() } }() c.sayhi(1, 0) }
ps:the key point how redirect error message on terminal screen file?
integer division 0 @ runtime in c not result in traditional panic()
can recover()
from. turns out c standard not define specific action taken in case; called "undefined behavior", , should working avoid (for instance, checking denominators).
but assume using example; turns out not example.
what can happen in c, , you're getting in case, operating system can throw signal. signals way operating system notify traditional c program went wrong, instance user hit control-c (asking terminate process) or floating-point exception occurred. can catch these go os/signal
package, note interrupt , kill signals available on oss (and interrupt can caught; kill cannot). see package documentation details.
Comments
Post a Comment