Skip to content

Commit c4cbe73

Browse files
committed
Add SIGTERM handler to show when test is killed by timeout
When a test hangs and is killed by `timeout`, Catch2 marks it as failed but the process exits before printing [ DONE ]. This made it unclear whether the test failed normally or was terminated. The signal handler prints a clear message when SIGTERM is received, making timeout-related failures obvious in CI logs.
1 parent 8951004 commit c4cbe73

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

tests/test_with_catch/catch.cpp

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,16 @@
44
#include <pybind11/embed.h>
55

66
#include <chrono>
7+
#include <csignal>
8+
#include <cstring>
79
#include <ctime>
810
#include <iomanip>
911
#include <sstream>
1012

13+
#ifndef _WIN32
14+
# include <unistd.h>
15+
#endif
16+
1117
// Silence MSVC C++17 deprecation warning from Catch regarding std::uncaught_exceptions (up to
1218
// catch 2.0.1; this should be fixed in the next catch release after 2.0.1).
1319
PYBIND11_WARNING_DISABLE_MSVC(4996)
@@ -100,9 +106,26 @@ std::string get_utc_timestamp() {
100106
return oss.str();
101107
}
102108

109+
#ifndef _WIN32
110+
// Signal handler to print a message when the process is terminated.
111+
// Uses only async-signal-safe functions.
112+
void termination_signal_handler(int sig) {
113+
const char *msg = "[ SIGNAL ] Process received SIGTERM\n";
114+
// write() is async-signal-safe, unlike std::cout
115+
(void) write(STDOUT_FILENO, msg, strlen(msg));
116+
// Re-raise with default handler to get proper exit status
117+
std::signal(sig, SIG_DFL);
118+
std::raise(sig);
119+
}
120+
#endif
121+
103122
} // namespace
104123

105124
int main(int argc, char *argv[]) {
125+
#ifndef _WIN32
126+
std::signal(SIGTERM, termination_signal_handler);
127+
#endif
128+
106129
// Setup for TEST_CASE in test_interpreter.cpp, tagging on a large random number:
107130
std::string updated_pythonpath("pybind11_test_with_catch_PYTHONPATH_2099743835476552");
108131
const char *preexisting_pythonpath = getenv("PYTHONPATH");

0 commit comments

Comments
 (0)