#include <QCoreApplication>
#include <QThread>
#include "hotcameramodule.h"


#ifndef WIN32

#include <execinfo.h>
#include <signal.h>
#include <stdio.h>
#include<unistd.h>
static void print_memory_base(void)
{
    char strbuf[512];
    pid_t pid = getpid();
    FILE *pf;

    sprintf(strbuf, "/proc/%d/maps", pid);
    pf = fopen(strbuf, "r");
    if(NULL == pf) return;
    while(fgets(strbuf, sizeof(strbuf), pf) != NULL) {
        printf("%s", strbuf);
    }
    fclose(pf);
}
static void print_stack_trace(void)
{
    char strbuf[256], *pstr;
    void *array[64];
    size_t size, i;
    char **strings;

    size = backtrace(array, 64);
    strings = backtrace_symbols(array, size);
    //printf ("Obtained %zd stack frames.\n", size);

    pstr = strbuf;
    for(i=1; i<=size; i++) {
        sprintf(pstr, "%08X:", (int)array[i]);
        pstr += strlen(pstr);
        if(0 == (i%8)) {
            printf("%s\n", strbuf);
            pstr = strbuf;
        }
    }
    if(pstr != strbuf) {
        printf("%s\n", strbuf);
    }

    for(i=0; i<size; i++) {
        printf("%s\n", strings[i]);
    }
    free(strings);
}
static const char *signal_name(int signum)
{
    struct sig_name_s
    {
        int signum;
        const char *name;
    };
    static const struct sig_name_s sig_name[] =
    {
        {SIGFPE, "SIGFPE"},
        {SIGINT, "SIGINT"},
        {SIGQUIT, "SIGQUIT"},
        {SIGILL, "SIGILL"},
        {SIGABRT, "SIGABRT"},
        {SIGPIPE, "SIGPIPE"},
        {SIGTERM, "SIGTERM"},
        {SIGTSTP, "SIGTSTP"},
        {SIGSEGV, "SIGSEGV"},
    };
    static const char *def_name = "unknown";

    for(size_t i=0; i<(sizeof(sig_name)/sizeof(sig_name[0])); i++)
    {
        if(signum == sig_name[i].signum)
            return sig_name[i].name;
    }

    return def_name;
}
static void signal_proc(int signum)
{
    const char *signame = signal_name(signum);

    printf("\n!!error!!catch signal %d(%s)\n", signum, signame);
    print_stack_trace();
    print_memory_base();

    signal(signum, SIG_DFL);
    raise(signum);
}

void debug_install_signal(void)
{
    signal(SIGFPE, signal_proc);		// 数学相关异常
    signal(SIGINT, signal_proc);        //中断进程  Ctrl-C
    signal(SIGQUIT, signal_proc);
    signal(SIGILL, signal_proc);		// 非法指令异常
    signal(SIGABRT, signal_proc);
    signal(SIGPIPE, signal_proc);       //向一个没有读进程的管道写数据
    signal(SIGTERM, signal_proc);       //软件终止信号
    signal(SIGTSTP, signal_proc);
    signal(SIGSEGV, signal_proc);		// 非法内存访问

}

#endif

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QThread t1, t2;

#ifndef WIN32

    debug_install_signal();
#endif

    HotCameraModule m1(0);
    HotCameraModule m2(1);
    m1.moveToThread(&t1);
    m2.moveToThread(&t2);
    t1.start();
    t2.start();

    return a.exec();
}
