Sending SIGTERM Signal to Only the Current Thread in Rust

245 Views Asked by At
use nix::sys::signal::{self, SigSet};

#[tokio::test]
async fn test_shutdown() {
let server = TestServer::new().await;
let proxy = ProxyUnderTest::new(server.listen_port).await;

sleep(std::time::Duration::from_millis(50));

let current_thread_id = unsafe { libc::pthread_self() };
println!("current_thread_id :{:?}", current_thread_id);

// Send the SIGTERM signal to the current thread.
nix::sys::signal::pthread_kill(current_thread_id, signal::Signal::SIGTERM).unwrap();

// Block the SIGTERM signal in the main thread.
let mut sigset = SigSet::empty();
sigset.add(signal::SIGTERM);
signal::pthread_sigmask(signal::SigmaskHow::SIG_BLOCK, Some(&sigset), None).unwrap();

// Wait for the proxy to shutdown.
let reason_opt = proxy.handle.await.unwrap();
assert_eq!(reason_opt, Some(ShutdownReason::GracefulShutdown));}

I want to send a SIGTERM signal to only the calling thread in my Rust test, but currently, the signal is received by all other threads spawned by cargo test. How can I fix this issue?

I've attempted to use pthread_kill to send the signal, but it seems to affect all threads. Additionally, I've tried blocking the SIGTERM signal in the main thread using SigSet and pthread_sigmask, but this hasn't resolved the problem.

How can I ensure that the SIGTERM signal is only received by the current thread? Any help would be greatly appreciated.

1

There are 1 best solutions below

0
On

POSIX offers pthread_cancel to terminate specific threads. Thread cancellation is difficult to use and typically requires support from all libraries in the process. Furthermore, on GNU/Linux, pthread_cancel involves stack unwinding, and the current Rust implementation does not support unwinding across FFI boundaries. There is a suggestion to add a C-unwind ABI. Even if that is fixed, pthread_cancel will remain difficult to use correctly.

For your specific case, the rusty-fork crate may be a better way to achieve test isolation using separate test processes, but I have not used it myself.