不从辅助线程c ++窗口调用SIGSEGV信号处理程序

时间:2015-04-30 15:39:07

标签: c++ multithreading

在下面的简单测试代码中,不会从辅助线程调用SIGSEGV信号处理程序,但如果崩溃在主线程中,则会调用它。在两种情况下都会调用SIGABRT信号的处理程序。 谁能解释为什么或我做错了什么?

#include <iostream>
#include <Windows.h>
#include <signal.h>

void signal_handler(int sig) 
{
    const char* name = NULL;
    switch( sig )
    {
        case SIGABRT: name = "SIGABRT";  break;
        case SIGSEGV: name = "SIGSEGV";  break;
    }
    std::cout << "Handler: Caught signal: " << name << std::endl;   
}

void install_signal_handlers()
{
    signal(SIGABRT, signal_handler);
    signal(SIGSEGV, signal_handler); 
    std::cout << "Signal handlers are installed" << std::endl;
}

void crash()
{
    //abort();
    //raise(SIGSEGV);
    try
    {
        int* ptr = NULL;
        *ptr = 2;
        std::cout << *ptr << std::endl;
    }
    catch (...) 
    {
        std::cout << "Caught exception: " << std::endl; 
    }   
} 

DWORD WINAPI thread(LPVOID lpParameter)
{
    //install_signal_handlers();    
    crash();

    return 0;
}

int main()
{
    install_signal_handlers(); 
    //crash();

    DWORD myThreadID;
    HANDLE myHandle = CreateThread(0, 0, thread, 0, 0, &myThreadID);

    if (myHandle == NULL) 
    {
        std::cout << "Failed to create thread" << std::endl; 
    }

    WaitForSingleObject(myHandle, INFINITE);
    CloseHandle(myHandle);

    return 0;
}

0 个答案:

没有答案