我想知道是否有一种简单的方法可以在不使用中间体 signal_handlers 的情况下捕获崩溃的线程的 id
我有以下代码
void signal_handler(int signal)
{
std::cout << "Caught the signal:" << signal << std::endl;
}
void handler_t1(int signal)
{
std::signal(SIGSEGV, signal_handler);
std::cout << "Thread 1 have received the signal: " << signal << std::endl;
std::raise(SIGSEGV);
}
void f1()
{
std::signal(SIGSEGV, handler_t1);
std::cout << "Begin thread 1" << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
std::raise(SIGSEGV);
std::cout << "end thread1" << std::endl;
}
void f2()
{
std::cout << "Begin thread 2" << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(3));
std::cout << "end thread2" << std::endl;
}
int main()
{
std::thread t1(f1);
std::thread t2(f2);
t1.join();
t2.join();
}
所以我得到
Begin thread 1Begin thread 2
Thread 1 have received the signal: 11
Caught the signal:11
end thread1
end thread2
但是如果我有 5 个线程,我可以避免创建 5 个处理程序吗?
编辑我的包含是
#include <thread>
#include <chrono>
#include <iostream>
#include <csignal>
编辑 我想我看起来像我找到的东西https://stackoverflow.com/a/16259324/2380470 但由于这个东西还不存在,我必须找到别的东西