yash-env 0.13.2

Yash shell execution environment interface
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
// This file is part of yash, an extended POSIX shell.
// Copyright (C) 2025 WATANABE Yuki
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

//! Signal-related functionality for the system module

#[cfg(doc)]
use super::{Concurrent, SharedSystem};
use super::{Pid, Result};
pub use crate::signal::{Name, Number, RawNumber};
use std::borrow::Cow;
use std::num::NonZero;
use std::ops::RangeInclusive;
use std::rc::Rc;

/// Trait for managing available signals
pub trait Signals {
    /// The signal number for `SIGABRT`
    const SIGABRT: Number;
    /// The signal number for `SIGALRM`
    const SIGALRM: Number;
    /// The signal number for `SIGBUS`
    const SIGBUS: Number;
    /// The signal number for `SIGCHLD`
    const SIGCHLD: Number;
    /// The signal number for `SIGCLD`, if available on the system
    const SIGCLD: Option<Number>;
    /// The signal number for `SIGCONT`
    const SIGCONT: Number;
    /// The signal number for `SIGEMT`, if available on the system
    const SIGEMT: Option<Number>;
    /// The signal number for `SIGFPE`
    const SIGFPE: Number;
    /// The signal number for `SIGHUP`
    const SIGHUP: Number;
    /// The signal number for `SIGILL`
    const SIGILL: Number;
    /// The signal number for `SIGINFO`, if available on the system
    const SIGINFO: Option<Number>;
    /// The signal number for `SIGINT`
    const SIGINT: Number;
    /// The signal number for `SIGIO`, if available on the system
    const SIGIO: Option<Number>;
    /// The signal number for `SIGIOT`
    const SIGIOT: Number;
    /// The signal number for `SIGKILL`
    const SIGKILL: Number;
    /// The signal number for `SIGLOST`, if available on the system
    const SIGLOST: Option<Number>;
    /// The signal number for `SIGPIPE`
    const SIGPIPE: Number;
    /// The signal number for `SIGPOLL`, if available on the system
    const SIGPOLL: Option<Number>;
    /// The signal number for `SIGPROF`
    const SIGPROF: Number;
    /// The signal number for `SIGPWR`, if available on the system
    const SIGPWR: Option<Number>;
    /// The signal number for `SIGQUIT`
    const SIGQUIT: Number;
    /// The signal number for `SIGSEGV`
    const SIGSEGV: Number;
    /// The signal number for `SIGSTKFLT`, if available on the system
    const SIGSTKFLT: Option<Number>;
    /// The signal number for `SIGSTOP`
    const SIGSTOP: Number;
    /// The signal number for `SIGSYS`
    const SIGSYS: Number;
    /// The signal number for `SIGTERM`
    const SIGTERM: Number;
    /// The signal number for `SIGTHR`, if available on the system
    const SIGTHR: Option<Number>;
    /// The signal number for `SIGTRAP`
    const SIGTRAP: Number;
    /// The signal number for `SIGTSTP`
    const SIGTSTP: Number;
    /// The signal number for `SIGTTIN`
    const SIGTTIN: Number;
    /// The signal number for `SIGTTOU`
    const SIGTTOU: Number;
    /// The signal number for `SIGURG`
    const SIGURG: Number;
    /// The signal number for `SIGUSR1`
    const SIGUSR1: Number;
    /// The signal number for `SIGUSR2`
    const SIGUSR2: Number;
    /// The signal number for `SIGVTALRM`
    const SIGVTALRM: Number;
    /// The signal number for `SIGWINCH`
    const SIGWINCH: Number;
    /// The signal number for `SIGXCPU`
    const SIGXCPU: Number;
    /// The signal number for `SIGXFSZ`
    const SIGXFSZ: Number;

    /// Returns the range of real-time signals supported by the system.
    ///
    /// If the system does not support real-time signals, returns `None`.
    ///
    /// The range is provided as a method rather than associated constants
    /// because some systems determine the range at runtime.
    #[must_use]
    fn sigrt_range(&self) -> Option<RangeInclusive<Number>>;

    /// List of all signal names and their numbers, excluding real-time signals
    ///
    /// This list contains all named signals declared in this trait, except for
    /// real-time signals. Each entry is a tuple of the signal name (without the
    /// `SIG` prefix) and its corresponding signal number. If a signal is not
    /// available on the system, its number is `None`.
    ///
    /// The signals are listed in alphabetical order by name (without the `SIG`
    /// prefix). Implementations that override this constant must preserve this
    /// ordering because the default implementation of
    /// [`str2sig`](Self::str2sig) relies on it to perform a binary search.
    const NAMED_SIGNALS: &'static [(&'static str, Option<Number>)] = &[
        ("ABRT", Some(Self::SIGABRT)),
        ("ALRM", Some(Self::SIGALRM)),
        ("BUS", Some(Self::SIGBUS)),
        ("CHLD", Some(Self::SIGCHLD)),
        ("CLD", Self::SIGCLD),
        ("CONT", Some(Self::SIGCONT)),
        ("EMT", Self::SIGEMT),
        ("FPE", Some(Self::SIGFPE)),
        ("HUP", Some(Self::SIGHUP)),
        ("ILL", Some(Self::SIGILL)),
        ("INFO", Self::SIGINFO),
        ("INT", Some(Self::SIGINT)),
        ("IO", Self::SIGIO),
        ("IOT", Some(Self::SIGIOT)),
        ("KILL", Some(Self::SIGKILL)),
        ("LOST", Self::SIGLOST),
        ("PIPE", Some(Self::SIGPIPE)),
        ("POLL", Self::SIGPOLL),
        ("PROF", Some(Self::SIGPROF)),
        ("PWR", Self::SIGPWR),
        ("QUIT", Some(Self::SIGQUIT)),
        ("SEGV", Some(Self::SIGSEGV)),
        ("STKFLT", Self::SIGSTKFLT),
        ("STOP", Some(Self::SIGSTOP)),
        ("SYS", Some(Self::SIGSYS)),
        ("TERM", Some(Self::SIGTERM)),
        ("THR", Self::SIGTHR),
        ("TRAP", Some(Self::SIGTRAP)),
        ("TSTP", Some(Self::SIGTSTP)),
        ("TTIN", Some(Self::SIGTTIN)),
        ("TTOU", Some(Self::SIGTTOU)),
        ("URG", Some(Self::SIGURG)),
        ("USR1", Some(Self::SIGUSR1)),
        ("USR2", Some(Self::SIGUSR2)),
        ("VTALRM", Some(Self::SIGVTALRM)),
        ("WINCH", Some(Self::SIGWINCH)),
        ("XCPU", Some(Self::SIGXCPU)),
        ("XFSZ", Some(Self::SIGXFSZ)),
    ];

    /// Returns an iterator over all real-time signals supported by the system.
    ///
    /// The iterator yields signal numbers in ascending order. If the system
    /// does not support real-time signals, the iterator yields no items.
    fn iter_sigrt(&self) -> impl DoubleEndedIterator<Item = Number> + use<Self> {
        let range = match self.sigrt_range() {
            Some(range) => range.start().as_raw()..=range.end().as_raw(),
            #[allow(clippy::reversed_empty_ranges)]
            None => 0..=-1,
        };
        // If NonZero implemented Step, we could use range.map(...)
        range.filter_map(|raw| NonZero::new(raw).map(Number::from_raw_unchecked))
    }

    /// Tests if a signal number is valid and returns its signal number.
    ///
    /// This function returns `Some(number)` if the signal number refers to a valid
    /// signal supported by the system. Otherwise, it returns `None`.
    #[must_use]
    fn to_signal_number<N: Into<RawNumber>>(&self, number: N) -> Option<Number> {
        fn inner<S: Signals + ?Sized>(system: &S, raw_number: RawNumber) -> Option<Number> {
            let non_zero = NonZero::new(raw_number)?;
            let number = Number::from_raw_unchecked(non_zero);
            (S::NAMED_SIGNALS
                .iter()
                .any(|signal| signal.1 == Some(number))
                || system
                    .sigrt_range()
                    .is_some_and(|range| range.contains(&number)))
            .then_some(number)
        }
        inner(self, number.into())
    }

    /// Converts a signal number to its string representation.
    ///
    /// This function returns `Some(name)` if the signal number refers to a valid
    /// signal supported by the system. Otherwise, it returns `None`.
    ///
    /// The returned name does not include the `SIG` prefix.
    /// Note that one signal number can have multiple names, in which case it is
    /// unspecified which name is returned.
    #[must_use]
    fn sig2str<N: Into<RawNumber>>(&self, signal: N) -> Option<Cow<'static, str>> {
        fn inner<S: Signals + ?Sized>(
            system: &S,
            raw_number: RawNumber,
        ) -> Option<Cow<'static, str>> {
            let number = Number::from_raw_unchecked(NonZero::new(raw_number)?);
            // The signals below are ordered roughly by frequency of use
            // so that common names are preferred for signals with multiple names.
            match () {
                () if number == S::SIGABRT => Some(Cow::Borrowed("ABRT")),
                () if number == S::SIGALRM => Some(Cow::Borrowed("ALRM")),
                () if number == S::SIGBUS => Some(Cow::Borrowed("BUS")),
                () if number == S::SIGCHLD => Some(Cow::Borrowed("CHLD")),
                () if number == S::SIGCONT => Some(Cow::Borrowed("CONT")),
                () if number == S::SIGFPE => Some(Cow::Borrowed("FPE")),
                () if number == S::SIGHUP => Some(Cow::Borrowed("HUP")),
                () if number == S::SIGILL => Some(Cow::Borrowed("ILL")),
                () if number == S::SIGINT => Some(Cow::Borrowed("INT")),
                () if number == S::SIGKILL => Some(Cow::Borrowed("KILL")),
                () if number == S::SIGPIPE => Some(Cow::Borrowed("PIPE")),
                () if number == S::SIGQUIT => Some(Cow::Borrowed("QUIT")),
                () if number == S::SIGSEGV => Some(Cow::Borrowed("SEGV")),
                () if number == S::SIGSTOP => Some(Cow::Borrowed("STOP")),
                () if number == S::SIGTERM => Some(Cow::Borrowed("TERM")),
                () if number == S::SIGTSTP => Some(Cow::Borrowed("TSTP")),
                () if number == S::SIGTTIN => Some(Cow::Borrowed("TTIN")),
                () if number == S::SIGTTOU => Some(Cow::Borrowed("TTOU")),
                () if number == S::SIGUSR1 => Some(Cow::Borrowed("USR1")),
                () if number == S::SIGUSR2 => Some(Cow::Borrowed("USR2")),
                () if Some(number) == S::SIGPOLL => Some(Cow::Borrowed("POLL")),
                () if number == S::SIGPROF => Some(Cow::Borrowed("PROF")),
                () if number == S::SIGSYS => Some(Cow::Borrowed("SYS")),
                () if number == S::SIGTRAP => Some(Cow::Borrowed("TRAP")),
                () if number == S::SIGURG => Some(Cow::Borrowed("URG")),
                () if number == S::SIGVTALRM => Some(Cow::Borrowed("VTALRM")),
                () if number == S::SIGWINCH => Some(Cow::Borrowed("WINCH")),
                () if number == S::SIGXCPU => Some(Cow::Borrowed("XCPU")),
                () if number == S::SIGXFSZ => Some(Cow::Borrowed("XFSZ")),
                () if Some(number) == S::SIGEMT => Some(Cow::Borrowed("EMT")),
                () if Some(number) == S::SIGINFO => Some(Cow::Borrowed("INFO")),
                () if Some(number) == S::SIGIO => Some(Cow::Borrowed("IO")),
                () if Some(number) == S::SIGLOST => Some(Cow::Borrowed("LOST")),
                () if Some(number) == S::SIGPWR => Some(Cow::Borrowed("PWR")),
                () if Some(number) == S::SIGSTKFLT => Some(Cow::Borrowed("STKFLT")),
                () if Some(number) == S::SIGTHR => Some(Cow::Borrowed("THR")),
                _ => {
                    let range = system.sigrt_range()?;
                    if number == *range.start() {
                        Some(Cow::Borrowed("RTMIN"))
                    } else if number == *range.end() {
                        Some(Cow::Borrowed("RTMAX"))
                    } else if range.contains(&number) {
                        let rtmin = range.start().as_raw();
                        let rtmax = range.end().as_raw();
                        if raw_number <= rtmin.midpoint(rtmax) {
                            let offset = raw_number - rtmin;
                            Some(Cow::Owned(format!("RTMIN+{}", offset)))
                        } else {
                            let offset = rtmax - raw_number;
                            Some(Cow::Owned(format!("RTMAX-{}", offset)))
                        }
                    } else {
                        None
                    }
                }
            }
        }
        inner(self, signal.into())
    }

    /// Converts a string representation of a signal to its signal number.
    ///
    /// This function returns `Some(number)` if the signal name is supported by
    /// the system. Otherwise, it returns `None`.
    ///
    /// The input name should not include the `SIG` prefix, and is case-sensitive.
    #[must_use]
    fn str2sig(&self, name: &str) -> Option<Number> {
        // Binary search on NAMED_SIGNALS
        if let Ok(index) = Self::NAMED_SIGNALS.binary_search_by_key(&name, |s| s.0) {
            return Self::NAMED_SIGNALS[index].1;
        }

        // Handle real-time signals
        enum BaseName {
            Rtmin,
            Rtmax,
        }
        let (basename, suffix) = if let Some(suffix) = name.strip_prefix("RTMIN") {
            (BaseName::Rtmin, suffix)
        } else if let Some(suffix) = name.strip_prefix("RTMAX") {
            (BaseName::Rtmax, suffix)
        } else {
            return None;
        };
        if !suffix.is_empty() && !suffix.starts_with(['+', '-']) {
            return None;
        }
        let range = self.sigrt_range()?;
        let base_raw = match basename {
            BaseName::Rtmin => range.start().as_raw(),
            BaseName::Rtmax => range.end().as_raw(),
        };
        let raw_number = if suffix.is_empty() {
            base_raw
        } else {
            let offset: RawNumber = suffix.parse().ok()?;
            base_raw.checked_add(offset)?
        };
        let number = Number::from_raw_unchecked(NonZero::new(raw_number)?);
        range.contains(&number).then_some(number)
    }

    /// Tests if a signal number is valid and returns its name and number.
    ///
    /// This function returns `Some((name, number))` if the signal number refers
    /// to a valid signal supported by the system. Otherwise, it returns `None`.
    ///
    /// Note that one signal number can have multiple names, in which case this
    /// function returns the name that is considered the most common.
    ///
    /// If you only need to tell whether a signal number is valid, use
    /// [`to_signal_number`](Self::to_signal_number), which is more efficient.
    #[must_use]
    fn validate_signal(&self, number: RawNumber) -> Option<(Name, Number)> {
        let number = Number::from_raw_unchecked(NonZero::new(number)?);
        let str_name = self.sig2str(number)?;
        Some((str_name.parse().ok()?, number))
    }

    /// Returns the signal name for the signal number.
    ///
    /// This function returns the signal name for the given signal number.
    ///
    /// If the signal number is invalid, this function panics. It may occur if
    /// the number is from a different system or was created without checking
    /// the validity.
    ///
    /// Note that one signal number can have multiple names, in which case this
    /// function returns the name that is considered the most common.
    #[must_use]
    fn signal_name_from_number(&self, number: Number) -> Name {
        self.validate_signal(number.as_raw()).unwrap().0
    }

    /// Gets the signal number from the signal name.
    ///
    /// This function returns the signal number corresponding to the signal name
    /// in the system. If the signal name is not supported, it returns `None`.
    #[must_use]
    fn signal_number_from_name(&self, name: Name) -> Option<Number> {
        self.str2sig(&name.as_string())
    }
}

/// Delegates the `Signals` trait to the contained instance of `S`
impl<S: Signals> Signals for Rc<S> {
    const SIGABRT: Number = S::SIGABRT;
    const SIGALRM: Number = S::SIGALRM;
    const SIGBUS: Number = S::SIGBUS;
    const SIGCHLD: Number = S::SIGCHLD;
    const SIGCLD: Option<Number> = S::SIGCLD;
    const SIGCONT: Number = S::SIGCONT;
    const SIGEMT: Option<Number> = S::SIGEMT;
    const SIGFPE: Number = S::SIGFPE;
    const SIGHUP: Number = S::SIGHUP;
    const SIGILL: Number = S::SIGILL;
    const SIGINFO: Option<Number> = S::SIGINFO;
    const SIGINT: Number = S::SIGINT;
    const SIGIO: Option<Number> = S::SIGIO;
    const SIGIOT: Number = S::SIGIOT;
    const SIGKILL: Number = S::SIGKILL;
    const SIGLOST: Option<Number> = S::SIGLOST;
    const SIGPIPE: Number = S::SIGPIPE;
    const SIGPOLL: Option<Number> = S::SIGPOLL;
    const SIGPROF: Number = S::SIGPROF;
    const SIGPWR: Option<Number> = S::SIGPWR;
    const SIGQUIT: Number = S::SIGQUIT;
    const SIGSEGV: Number = S::SIGSEGV;
    const SIGSTKFLT: Option<Number> = S::SIGSTKFLT;
    const SIGSTOP: Number = S::SIGSTOP;
    const SIGSYS: Number = S::SIGSYS;
    const SIGTERM: Number = S::SIGTERM;
    const SIGTHR: Option<Number> = S::SIGTHR;
    const SIGTRAP: Number = S::SIGTRAP;
    const SIGTSTP: Number = S::SIGTSTP;
    const SIGTTIN: Number = S::SIGTTIN;
    const SIGTTOU: Number = S::SIGTTOU;
    const SIGURG: Number = S::SIGURG;
    const SIGUSR1: Number = S::SIGUSR1;
    const SIGUSR2: Number = S::SIGUSR2;
    const SIGVTALRM: Number = S::SIGVTALRM;
    const SIGWINCH: Number = S::SIGWINCH;
    const SIGXCPU: Number = S::SIGXCPU;
    const SIGXFSZ: Number = S::SIGXFSZ;

    #[inline]
    fn sigrt_range(&self) -> Option<RangeInclusive<Number>> {
        (self as &S).sigrt_range()
    }

    const NAMED_SIGNALS: &'static [(&'static str, Option<Number>)] = S::NAMED_SIGNALS;

    #[inline]
    fn iter_sigrt(&self) -> impl DoubleEndedIterator<Item = Number> + use<S> {
        (self as &S).iter_sigrt()
    }
    #[inline]
    fn to_signal_number<N: Into<RawNumber>>(&self, number: N) -> Option<Number> {
        (self as &S).to_signal_number(number)
    }
    #[inline]
    fn sig2str<N: Into<RawNumber>>(&self, signal: N) -> Option<Cow<'static, str>> {
        (self as &S).sig2str(signal)
    }
    #[inline]
    fn str2sig(&self, name: &str) -> Option<Number> {
        (self as &S).str2sig(name)
    }
    #[inline]
    fn validate_signal(&self, number: RawNumber) -> Option<(Name, Number)> {
        (self as &S).validate_signal(number)
    }
    #[inline]
    fn signal_name_from_number(&self, number: Number) -> Name {
        (self as &S).signal_name_from_number(number)
    }
    #[inline]
    fn signal_number_from_name(&self, name: Name) -> Option<Number> {
        (self as &S).signal_number_from_name(name)
    }
}

/// Operation applied to the signal blocking mask
///
/// This enum corresponds to the operations of the `sigprocmask` system call and
/// is used in the [`Sigmask::sigmask`] method.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum SigmaskOp {
    /// Add signals to the mask (`SIG_BLOCK`)
    Add,
    /// Remove signals from the mask (`SIG_UNBLOCK`)
    Remove,
    /// Set the mask to the given signals (`SIG_SETMASK`)
    Set,
}

/// Trait for managing signal blocking mask
pub trait Sigmask: Signals {
    /// Gets and/or sets the signal blocking mask.
    ///
    /// This trait is usually not used directly. Instead, it is used by
    /// [`Concurrent`] and [`SharedSystem`] to configure signal handling
    /// behavior of the process.
    ///
    /// This is a thin wrapper around the [`sigprocmask` system
    /// call](https://pubs.opengroup.org/onlinepubs/9799919799/functions/pthread_sigmask.html).
    /// If `op` is `Some`, this function updates the signal blocking mask by
    /// applying the given `SigmaskOp` and signal set to the current mask. If
    /// `op` is `None`, this function does not change the mask.
    /// If `old_mask` is `Some`, this function sets the previous mask to it.
    ///
    /// The return type is a future so that
    /// [virtual systems](crate::system::virtual) can simulate termination or
    /// suspension of the process that may be caused by a signal delivered as a
    /// result of changing (for example, unblocking) the signal mask. In the
    /// [real system](super::real), this function does not work asynchronously
    /// and returns a ready `Future` with the result of the underlying system
    /// call. See the [module-level documentation](super) for details.
    fn sigmask(
        &self,
        op: Option<(SigmaskOp, &[Number])>,
        old_mask: Option<&mut Vec<Number>>,
    ) -> impl Future<Output = Result<()>> + use<Self>;
}

/// Delegates the `Sigmask` trait to the contained instance of `S`
impl<S: Sigmask> Sigmask for Rc<S> {
    #[inline]
    fn sigmask(
        &self,
        op: Option<(SigmaskOp, &[Number])>,
        old_mask: Option<&mut Vec<Number>>,
    ) -> impl Future<Output = Result<()>> + use<S> {
        (self as &S).sigmask(op, old_mask)
    }
}

/// How the shell process responds to a signal
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum Disposition {
    /// Perform the default action for the signal.
    ///
    /// The default action depends on the signal. For example, `SIGINT` causes
    /// the process to terminate, and `SIGTSTP` causes the process to stop.
    #[default]
    Default,
    /// Ignore the signal.
    Ignore,
    /// Catch the signal.
    Catch,
}

/// Trait for getting signal dispositions
pub trait GetSigaction: Signals {
    /// Gets the disposition for a signal.
    ///
    /// This is an abstract wrapper around the [`sigaction` system
    /// call](https://pubs.opengroup.org/onlinepubs/9799919799/functions/sigaction.html).
    /// This function returns the current disposition if successful.
    ///
    /// To change the disposition, use [`Sigaction::sigaction`].
    fn get_sigaction(&self, signal: Number) -> Result<Disposition>;
}

/// Delegates the `GetSigaction` trait to the contained instance of `S`
impl<S: GetSigaction> GetSigaction for Rc<S> {
    #[inline]
    fn get_sigaction(&self, signal: Number) -> Result<Disposition> {
        (self as &S).get_sigaction(signal)
    }
}

/// Trait for managing signal dispositions
pub trait Sigaction: GetSigaction {
    /// Gets and sets the disposition for a signal.
    ///
    /// This trait is usually not used directly. Instead, it is used by
    /// [`Concurrent`] and [`SharedSystem`] to configure signal handling
    /// behavior of the process.
    ///
    /// This is an abstract wrapper around the [`sigaction` system
    /// call](https://pubs.opengroup.org/onlinepubs/9799919799/functions/sigaction.html).
    /// This function returns the previous disposition if successful.
    ///
    /// When you set the disposition to `Disposition::Catch`, signals sent to
    /// this process are accumulated in `self` and made available from
    /// [`caught_signals`](CaughtSignals::caught_signals).
    ///
    /// To get the current disposition without changing it, use
    /// [`GetSigaction::get_sigaction`].
    fn sigaction(&self, signal: Number, action: Disposition) -> Result<Disposition>;
}

/// Delegates the `Sigaction` trait to the contained instance of `S`
impl<S: Sigaction> Sigaction for Rc<S> {
    #[inline]
    fn sigaction(&self, signal: Number, action: Disposition) -> Result<Disposition> {
        (self as &S).sigaction(signal, action)
    }
}

/// Trait for examining signals caught by the process
///
/// Implementors of this trait usually also implement [`Sigaction`] to allow
/// setting which signals are caught.
pub trait CaughtSignals: Signals {
    /// Returns signals this process has caught, if any.
    ///
    /// This trait is usually not used directly. Instead, it is used by
    /// [`Concurrent`] and [`SharedSystem`] to collect signals caught by the
    /// process.
    ///
    /// Implementors of this trait usually also implement [`Sigaction`] to allow
    /// setting which signals are caught.
    /// To catch a signal, you firstly install a signal handler by calling
    /// [`Sigaction::sigaction`] with [`Disposition::Catch`]. Once the handler
    /// is ready, signals sent to the process are accumulated in the
    /// implementor. Calling this function retrieves the list of caught signals.
    ///
    /// This function clears the internal list of caught signals, so a next call
    /// will return an empty list unless another signal is caught since the
    /// first call. Because the list size may be limited, you should call this
    /// function periodically before the list gets full, in which case further
    /// caught signals are silently ignored.
    ///
    /// Note that signals become pending if sent while blocked by
    /// [`Sigmask::sigmask`]. They must be unblocked so that they are caught and
    /// made available from this function.
    fn caught_signals(&self) -> Vec<Number>;
}

/// Delegates the `CaughtSignals` trait to the contained instance of `S`
impl<S: CaughtSignals> CaughtSignals for Rc<S> {
    #[inline]
    fn caught_signals(&self) -> Vec<Number> {
        (self as &S).caught_signals()
    }
}

/// Trait for sending signals to processes
pub trait SendSignal: Signals {
    /// Sends a signal.
    ///
    /// This is a thin wrapper around the [`kill` system
    /// call](https://pubs.opengroup.org/onlinepubs/9799919799/functions/kill.html).
    /// If `signal` is `None`, permission to send a signal is checked, but no
    /// signal is sent.
    ///
    /// The virtual system version of this function blocks the calling thread if
    /// the signal stops or terminates the current process, hence returning a
    /// future. See [`VirtualSystem::kill`] for details.
    ///
    /// [`VirtualSystem::kill`]: crate::system::virtual::VirtualSystem::kill
    fn kill(
        &self,
        target: Pid,
        signal: Option<Number>,
    ) -> impl Future<Output = Result<()>> + use<Self>;

    /// Sends a signal to the current process.
    ///
    /// This is a thin wrapper around the `raise` system call.
    ///
    /// The virtual system version of this function blocks the calling thread if
    /// the signal stops or terminates the current process, hence returning a
    /// future. See [`VirtualSystem::kill`] for details.
    ///
    /// [`VirtualSystem::kill`]: crate::system::virtual::VirtualSystem::kill
    fn raise(&self, signal: Number) -> impl Future<Output = Result<()>> + use<Self>;
}

/// Delegates the `SendSignal` trait to the contained instance of `S`
impl<S: SendSignal> SendSignal for Rc<S> {
    #[inline]
    fn kill(
        &self,
        target: Pid,
        signal: Option<Number>,
    ) -> impl Future<Output = Result<()>> + use<S> {
        (self as &S).kill(target, signal)
    }
    #[inline]
    fn raise(&self, signal: Number) -> impl Future<Output = Result<()>> + use<S> {
        (self as &S).raise(signal)
    }
}