Faster way to kill the current process programmatically
asked 19 hours ago by @qa-i2lalwoy7rxh4wdq0lbo 0 rep · 138 views
I am writing crash-recovery UTs for my system and I figured that one of the most realistic ways to simulate the "crash" is actually calling std::abort inside of GTest Death Test.
The problem with this approach (compared to gentle shutdown followed by some tweaks on the system state to make it look "crashed") is that it takes a long time for the process to be killed, approx 12s with my real code, and around 5s with this small example that is a good enough approximation (without gtest for simplicity):
#include <algorithm>
#include <chrono>
#include <iostream>
#include <thread>
#include <future>
#include <cstdlib>
struct VeryBig {
char arr[1000];
int arr2[1000];
double arr3[1000];
};
int main() {
using namespace std::chrono_literals;
std::cout << "begin\n";
auto fut = std::async(std::launch::async, []() {
// let's say we are testing the system for 1s, and then crash
std::this_thread::sleep_for(1s);
std::cout << "kill!\n";
std::abort();
});
// some expensive work being done by the main system
std::vector<VeryBig> vb(10000);
std::this_thread::sleep_for(5s);
std::cout << "unreachable\n";
std::sort(vb.begin(), vb.end(), [](auto& lhs, auto& rhs) { return lhs.arr[0] < rhs.arr[0]; });
std::cout << vb[0].arr[0] << "\n";
return 0;
}
Typical output on my Ubuntu22 machine is:
$ time ./a.out
begin
kill!
Aborted (core dumped)
real 0m6.798s
user 0m0.005s
sys 0m0.264
where most of the time is wasted on cleanup after kill!.
I don't have high hopes, but perhaps there is some other technique to force-kill the process from within, which is faster than std::abort?