サーチ…
備考
Rustには、OSシグナルを流すための適切で慣用的で安全な方法はありませんが、シグナル処理を提供するいくつかの箱がありますが、それらは高度に実験的で安全ではありませんので、使用する際には注意してください。
しかしrust-lang / rfcsリポジトリには、 錆のネイティブシグナル処理の実装についての議論があります。
RFCの議論: https : //github.com/rust-lang/rfcs/issues/1368
チャン信号クレートによる信号処理
chan-signal crateは、チャンネルを使用してOS信号を処理するソリューションを提供しますが、このクレートは実験的なものであり、 慎重に使用する必要があります。
例はBurntSushi / chan-signalから取ったものです 。
#[macro_use]
extern crate chan;
extern crate chan_signal;
use chan_signal::Signal;
fn main() {
// Signal gets a value when the OS sent a INT or TERM signal.
let signal = chan_signal::notify(&[Signal::INT, Signal::TERM]);
// When our work is complete, send a sentinel value on `sdone`.
let (sdone, rdone) = chan::sync(0);
// Run work.
::std::thread::spawn(move || run(sdone));
// Wait for a signal or for work to be done.
chan_select! {
signal.recv() -> signal => {
println!("received signal: {:?}", signal)
},
rdone.recv() => {
println!("Program completed normally.");
}
}
}
fn run(_sdone: chan::Sender<()>) {
println!("Running work for 5 seconds.");
println!("Can you send a signal quickly enough?");
// Do some work.
::std::thread::sleep_ms(5000);
// _sdone gets dropped which closes the channel and causes `rdone`
// to unblock.
}
nix crateを使って信号を処理する。
nix crateはシグナルを処理するためのUNIX Rust APIを提供しますが、 安全ではない錆を使用する必要がありますので注意が必要です。
use nix::sys::signal;
extern fn handle_sigint(_:i32) {
// Be careful here...
}
fn main() {
let sig_action = signal::SigAction::new(handle_sigint,
signal::SockFlag::empty(),
signal::SigSet::empty());
signal::sigaction(signal::SIGINT, &sig_action);
}
Tokioの例
トキオ信号クレートは信号処理のためのトキオベースのソリューションを提供します。しかしそれはまだ初期の段階です。
extern crate futures;
extern crate tokio_core;
extern crate tokio_signal;
use futures::{Future, Stream};
use tokio_core::reactor::Core
use tokio_signal::unix::{self as unix_signal, Signal};
use std::thread::{self, sleep};
use std::time::Duration;
use std::sync::mpsc::{channel, Receiver};
fn run(signals: Receiver<i32>) {
loop {
if let Some(signal) = signals.try_recv() {
eprintln!("received {} signal");
}
sleep(Duration::from_millis(1));
}
}
fn main() {
// Create channels for sending and receiving signals
let (signals_tx, signals_rx) = channel();
// Execute the program with the receiving end of the channel
// for listening to any signals that are sent to it.
thread::spawn(move || run(signals_rx));
// Create a stream that will select over SIGINT, SIGTERM, and SIGHUP signals.
let signals = Signal::new(unix_signal::SIGINT, &handle).flatten_stream()
.select(Signal::new(unix_signal::SIGTERM, &handle).flatten_stream())
.select(Signal::new(unix_signal::SIGHUP, &handle).flatten_stream());
// Execute the event loop that will listen for and transmit received
// signals to the shell.
core.run(signals.for_each(|signal| {
let _ = signals_tx.send(signal);
Ok(())
})).unwrap();
}
Modified text is an extract of the original Stack Overflow Documentation
ライセンスを受けた CC BY-SA 3.0
所属していない Stack Overflow