-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathblocking-signals-minimal.rs
More file actions
44 lines (36 loc) · 1.59 KB
/
blocking-signals-minimal.rs
File metadata and controls
44 lines (36 loc) · 1.59 KB
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
//! See `blocking-signals-demonstration.rs` for a more detailed example of
//! how signal blocking works at runtime, and why you might want to do it.
//!
//! Use this example for copy + paste code snippets.
use mem_isolate::{MemIsolateError, execute_in_isolated_process};
use nix::errno::Errno;
use nix::sys::signal::{SigSet, SigmaskHow, sigprocmask};
fn main() -> Result<(), MemIsolateError> {
// Block all signals right before calling `mem_isolate::execute_in_isolated_process()`
// This ensures the main program won't be killed leaving an orphaned child process
let (block_signals, restore_signals) = get_block_and_restore_signal_closures();
block_signals().expect("Failed to block signals");
// Run your code in an isolated process. NOTE: The child process created by
// `fork()` inside `execute_in_isolated_process()` will inherit the signal
// mask set by main process just above.
let result = execute_in_isolated_process(|| ());
// Restore the signal mask, unblocking all signals
restore_signals().expect("Failed to restore signals");
result
}
fn get_block_and_restore_signal_closures() -> (
impl FnOnce() -> Result<(), Errno>,
impl FnOnce() -> Result<(), Errno>,
) {
let all_signals = SigSet::all();
let mut old_signals = SigSet::empty();
let block_signals = move || {
sigprocmask(
SigmaskHow::SIG_SETMASK,
Some(&all_signals),
Some(&mut old_signals),
)
};
let restore_signals = move || sigprocmask(SigmaskHow::SIG_SETMASK, Some(&old_signals), None);
(block_signals, restore_signals)
}