Skip to main content

dope_sys/thread/signal/
raw.rs

1use std::{fmt, os::fd};
2
3use o3::mem::slot;
4
5use crate::thread::{
6    Thread,
7    signal::{Acquire, CLAIMED, ReleaseFault, Source},
8};
9
10#[derive(Debug)]
11pub enum Rejected<'a, R> {
12    Failed(Acquire),
13    Retained {
14        cause: Acquire,
15        receiver: slot::Occupied<'a, R>,
16    },
17}
18
19impl<R> From<Acquire> for Rejected<'_, R> {
20    fn from(cause: Acquire) -> Self {
21        Self::Failed(cause)
22    }
23}
24
25/// # Safety
26/// `is_main` must identify the original thread. Failed acquisition must
27/// return a receiver capable of restoring every changed signal policy.
28pub unsafe trait Receiver: fmt::Debug + fd::AsFd + Sized {
29    /// Returns whether this receiver is being installed on the process's original thread.
30    fn is_main() -> bool;
31
32    /// # Safety
33    /// Retain exclusive process SIGTERM/SIGINT authority through restoration, including failed acquisition.
34    /// Start workers after acquisition and join them before restoration.
35    unsafe fn try_new(
36        vacant: slot::raw::Vacant<'_, Self>,
37    ) -> Result<slot::Occupied<'_, Self>, Rejected<'_, Self>>;
38    fn try_wait<B: Thread<Receiver = Self>>(source: &Source<'_, B>) -> Result<(), crate::Errno>;
39
40    /// Restores the previous signal policy, retaining its owner on failure.
41    fn restore(&self) -> Result<(), ReleaseFault>;
42}
43
44pub(super) fn acquire<R: Receiver>(
45    vacant: slot::raw::Vacant<'_, R>,
46) -> Result<slot::Occupied<'_, R>, Rejected<'_, R>> {
47    if !R::is_main() {
48        return Err(Acquire::Thread.into());
49    }
50    if CLAIMED.replace(true) {
51        return Err(Acquire::Busy.into());
52    }
53    // SAFETY: this original thread holds the process claim through native restoration.
54    let acquired = unsafe { R::try_new(vacant) };
55    if matches!(acquired, Err(Rejected::Failed(_))) {
56        CLAIMED.set(false);
57    }
58    acquired
59}