It's easy to redirect a golang panic to a file, just use recover() to capture that and use syscall.Dup2() to redirect. But when it comes to a C panic, it seems to be useless, just like the image, the console will show the error message like "fatal error: unexpected signal during runtime execution" and some stack message. How to redirect these error message to a 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 to 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 is how to redirect the error message on the terminal screen to a file?