diff --git a/src/runtime.md b/src/runtime.md index a281d50fb..678fdfc72 100644 --- a/src/runtime.md +++ b/src/runtime.md @@ -55,6 +55,60 @@ runtime with the [set_hook] function. The *`global_allocator` attribute* is used on a [static item] implementing the [`GlobalAlloc`] trait to set the global allocator. +## The `#[unix_sigpipe = "sig_dfl"]` attribute + +The *`#[unix_sigpipe = "sig_dfl"]` attribute* is used on [main functions] and +controls how the `SIGPIPE` signal is configured on unix platforms before the +main function is invoked. + +By default, the `SIGPIPE` signal is configured to be ignored (`SIG_IGN`) to +allow errors to be generated. By applying `#[unix_sigpipe = "sig_dfl"]` on the +main function, the `SIGPIPE` signal is instead configured to be handled in the +default way (`SIG_DFL`), which means killing the process that receives +`SIGPIPE`. Note that if the process is killed by `SIGPIPE`, destructors will +[not run]. + +### Example + +The program + +```rust +fn main() { + for _ in 1..10_000 { + println!("hello world"); + } +} +``` + +will panic if its output is piped to `head`, since `println!` does not handle +the error that is generated when its stdout is closed by `head` exiting: + +```console +$ ./main | head +hello world +thread 'main' panicked at library/std/src/io/stdio.rs:1030:9: +failed printing to stdout: Broken pipe (os error 32) +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace +``` + +If we apply `#[unix_sigpipe = "sig_dfl"]`, `SIGPIPE` will be configured to use +the `SIG_DFL` handler and the program will be killed when receiving the +generated `SIGPIPE` signal: + +```rust +#[unix_sigpipe = "sig_dfl"] +fn main() { + for _ in 1..10_000 { + println!("hello world"); + } +} +``` + +```console +$ ./main | head +hello world +``` + ## The `windows_subsystem` attribute The *`windows_subsystem` attribute* may be applied at the crate level to set @@ -80,6 +134,8 @@ display a console window on startup. It will run detached from any existing cons [abort]: ../book/ch09-01-unrecoverable-errors-with-panic.html [attribute]: attributes.md [crate types]: linkage.md +[main functions]: crates-and-source-files.md#main-functions +[not run]: behavior-not-considered-unsafe.md#exiting-without-calling-destructors [set_hook]: ../std/panic/fn.set_hook.html [static item]: items/static-items.md [subsystem]: https://msdn.microsoft.com/en-us/library/fcc1zstk.aspx