├── .gitignore ├── .travis.yml ├── Cargo.toml ├── LICENSE ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── bulk.yaml ├── examples ├── poll_for_signal.rs ├── restarter.rs └── run.rs ├── src ├── exec_handler.rs ├── ffi.rs ├── lib.rs └── trap.rs └── vagga.yaml /.gitignore: -------------------------------------------------------------------------------- 1 | /.vagga 2 | /target 3 | /Cargo.lock 4 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | matrix: 3 | include: 4 | - rust: stable 5 | os: linux 6 | - rust: beta 7 | os: linux 8 | - rust: nightly 9 | os: linux 10 | - rust: stable 11 | os: osx 12 | sudo: false 13 | env: 14 | - secure: "qyDQIk43cmSgZOtl4Po7DnjIvKOv61my2XAUQk3aXVBgyMqVNA2EyT2wK5Iu+ibkKgdwFiBZWCIfDKTWk9hNWBXR6GryKqlgZd8ey6FXBl4kNmiewwkhQIZwBTxiCDHeZPw/XGbTuCMYIn7j4HqvHWFgPfjwT9ivVquOhIdg6zCxt4I6Uu+kaSaBFeK+GXzVi+sUvgso7A0pS+i/JsCYW+o2moBGebStys+s4wd2AIMT2GDC1YVms4mmIKB4DN4qwGmtxHv/5ftoDN8uAvUhi+AOqDVbsyMi6Dl6d6ln8H91uCADSV2A/c0L3wAX0ajswyg6idwXjWxHVlki5EyuZdUf3tjuKo0qgiThKCYt3TbJSgiJ0P/G11JdCLURRe6UGYcatpjJe2omXQBkuF0oSb6lufxvQrOFr+jIrDZBmBEni8/u3eFatBAMOn4f42dtJsC7mK9UUijy+CsgMMkRJWDEU+jS+gXWvUOyTbcxE+pISlDvqrPChMCiW+sp+SjCsVZ53WOAcE7BYrRiP/t9Tac+SllJSCbkT6069IJuA2zzrUFHYsPmj7c9nlrG42Y0b7FCmLUYiCAROHDIqDFToJ86D/oFz2423S6+davre5GNwmLmvgaZ6UuEXNwHovDQnBvJIuQiewuU5njmN+3YxphE6qMiUri31uvjHbkPsCs=" 15 | 16 | deploy: 17 | provider: script 18 | script: "cargo publish --token=$CARGO_TOKEN" 19 | on: 20 | rust: stable 21 | os: linux 22 | tags: true 23 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "signal" 3 | description = """ 4 | The higher-level abstractions around unix signals 5 | """ 6 | version = "0.7.0" 7 | license = "MIT/Apache-2.0" 8 | authors = ["Paul Colomiets "] 9 | homepage = "https://github.com/tailhook/signal" 10 | repository = "https://github.com/tailhook/signal" 11 | documentation = "https://docs.rs/signal" 12 | 13 | [dependencies] 14 | nix = "0.14.1" 15 | libc = "0.2.12" 16 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2015 Paul Colomiets 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in 11 | all copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | THE SOFTWARE. 20 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2015 The signal Developers 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in all 11 | copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | SOFTWARE. 20 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Rust Signal 2 | =========== 3 | 4 | [Docs](https://docs.rs/signal/) | 5 | [Github](https://github.com/tailhook/signal/) | 6 | [Crate](https://crates.io/crates/signal) 7 | 8 | A higher-level library for handling unix signals. Currently more focused on 9 | writing process supervisors, but may be used (and extended) for other purposes 10 | too. 11 | 12 | License 13 | ======= 14 | 15 | Licensed under either of 16 | 17 | * Apache License, Version 2.0, (./LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0) 18 | * MIT license (./LICENSE-MIT or http://opensource.org/licenses/MIT) 19 | 20 | at your option. 21 | 22 | Contribution 23 | ------------ 24 | 25 | Unless you explicitly state otherwise, any contribution intentionally 26 | submitted for inclusion in the work by you, as defined in the Apache-2.0 27 | license, shall be dual licensed as above, without any additional terms or 28 | conditions. 29 | -------------------------------------------------------------------------------- /bulk.yaml: -------------------------------------------------------------------------------- 1 | minimum-bulk: v0.4.5 2 | 3 | versions: 4 | 5 | - file: Cargo.toml 6 | block-start: ^\[package\] 7 | block-end: ^\[.*\] 8 | regex: ^version\s*=\s*"(\S+)" 9 | -------------------------------------------------------------------------------- /examples/poll_for_signal.rs: -------------------------------------------------------------------------------- 1 | extern crate signal; 2 | extern crate nix; 3 | 4 | use std::time::{Instant, Duration}; 5 | use std::thread::sleep; 6 | 7 | use nix::sys::signal::{SIGINT}; 8 | 9 | use signal::trap::Trap; 10 | 11 | 12 | #[cfg(target_os="linux")] 13 | fn main() { 14 | let trap = Trap::trap(&[SIGINT]); 15 | loop { 16 | if let Some(SIGINT) = trap.wait(Instant::now()) { 17 | println!("Gracefully interrupted..."); 18 | break; 19 | } 20 | sleep(Duration::from_millis(100)); 21 | } 22 | } 23 | 24 | #[cfg(not(target_os="linux"))] 25 | fn main() { 26 | println!("unfortunately this example works only for linux"); 27 | } 28 | -------------------------------------------------------------------------------- /examples/restarter.rs: -------------------------------------------------------------------------------- 1 | extern crate signal; 2 | extern crate nix; 3 | 4 | use std::time::Duration; 5 | use std::thread::sleep; 6 | use std::str::FromStr; 7 | use std::env::{args, vars_os, current_exe}; 8 | 9 | use nix::sys::signal::SIGQUIT; 10 | 11 | 12 | fn main() { 13 | let num: u64 = FromStr::from_str( 14 | &args().skip(1).next().unwrap_or("0".to_string()) 15 | ).unwrap(); 16 | println!("Restared {} times", num); 17 | signal::exec_handler::set_command_line( 18 | current_exe().unwrap(), 19 | &["restarter".to_string(), (num+1).to_string()], 20 | vars_os()); 21 | signal::exec_handler::set_handler(&[SIGQUIT], true).unwrap(); 22 | sleep(Duration::new(10000, 0)); 23 | } 24 | -------------------------------------------------------------------------------- /examples/run.rs: -------------------------------------------------------------------------------- 1 | extern crate signal; 2 | extern crate nix; 3 | 4 | use std::env::{args}; 5 | use std::process::Command; 6 | 7 | use nix::Error; 8 | use nix::errno::Errno; 9 | use nix::sys::signal::{SIGTERM, SIGINT, SIGCHLD}; 10 | use nix::sys::wait::{waitpid, WaitPidFlag}; 11 | use nix::sys::wait::WaitStatus::{Exited, Signaled, StillAlive}; 12 | use nix::libc::{c_int}; 13 | 14 | 15 | fn main() { 16 | let args = args().skip(1).collect::>(); 17 | let commandlines = args.split(|x| &x[..] == "---"); 18 | 19 | for cline in commandlines { 20 | let mut cmd = Command::new(&cline[0]); 21 | cmd.args(&cline[1..]); 22 | println!("Starting {:?}", cmd); 23 | cmd.spawn().unwrap(); 24 | } 25 | 26 | let trap = signal::trap::Trap::trap(&[SIGTERM, SIGINT, SIGCHLD]); 27 | for sig in trap { 28 | match sig { 29 | SIGCHLD => { 30 | // Current std::process::Command ip does not have a way to find 31 | // process id, so we just wait until we have no children 32 | loop { 33 | match waitpid(None, Some(WaitPidFlag::WNOHANG)) { 34 | Ok(Exited(pid, status)) => { 35 | println!("{} exited with status {}", pid, status); 36 | continue; 37 | } 38 | Ok(Signaled(pid, sig, _)) => { 39 | println!("{} killed by {}", pid, sig as c_int); 40 | continue; 41 | } 42 | Ok(StillAlive) => { break; } 43 | Ok(status) => { 44 | println!("Temporary status {:?}", status); 45 | continue; 46 | } 47 | Err(Error::Sys(Errno::ECHILD)) => { 48 | return; 49 | } 50 | Err(e) => { 51 | panic!("Error {:?}", e); 52 | } 53 | } 54 | } 55 | } 56 | sig => { 57 | println!("Stopping because of {}", sig as c_int); 58 | // At this stage is probably good idea to forward signal 59 | // to children and wait until they all dead, but we omit 60 | // it for brevity 61 | break; 62 | } 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/exec_handler.rs: -------------------------------------------------------------------------------- 1 | //! Set a signal handler that executes command-line 2 | //! 3 | //! This is supposed to work on panics, deadlocks and event many kinds of 4 | //! memory errors. But may leak file descriptors which have no CLOEXEC flag set 5 | //! 6 | //! This is used as fail-safe signal handler for the supervisors, which are 7 | //! able to re-execute in place and continue to work. Also may be used for 8 | //! configuration reloading signal (e.g. SIGHUP) if appropriate. 9 | 10 | use std::io::Write; 11 | use std::mem::{forget, transmute}; 12 | use std::ptr::{null}; 13 | use std::ffi::CString; 14 | use std::env::{current_exe, args_os, vars_os}; 15 | 16 | use nix; 17 | use libc::{execve, c_char, pid_t, getpid, c_int}; 18 | use nix::sys::signal::{sigaction, SigAction, Signal, SigSet, SaFlags}; 19 | use nix::sys::signal::{pthread_sigmask, SigmaskHow, SigHandler}; 20 | 21 | use ffi::{ToCString}; 22 | 23 | 24 | static mut EXEC_COMMAND_LINE: *const ExecCommandLine = 25 | 0usize as *const ExecCommandLine; 26 | 27 | #[allow(unused)] 28 | struct ExecCommandLine { 29 | program: CString, 30 | args: Vec, 31 | c_args: Vec<*const c_char>, 32 | env: Vec, 33 | c_env: Vec<*const c_char>, 34 | pid: pid_t, 35 | } 36 | 37 | /// Sets command-line and environment to execute when signal happens 38 | /// 39 | /// If nothing is set current command-line is used. 40 | /// 41 | /// You may change it freely even after calling set_handler. But only single 42 | /// command-line may be set for all signal handlers used in this module. 43 | /// 44 | /// Since version v0.3.0 command-line is executed only if pid of a process 45 | /// matches original pid where set_handler was called. I.e. you need to 46 | /// set_handler again for forked process if that is desired. 47 | pub fn set_command_line(program: P, args: A, environ: E) 48 | where P: ToCString, 49 | Ai: ToCString, 50 | A: IntoIterator, 51 | Ek: ToCString, 52 | Ev: ToCString, 53 | E: IntoIterator, 54 | { 55 | let args = args.into_iter().map(|x| x.to_cstring()).collect::>(); 56 | let mut c_args = args.iter().map(|x| x.as_ptr()).collect::>(); 57 | c_args.push(null()); 58 | let env = environ.into_iter().map(|(k, v)| { 59 | let mut pair = Vec::new(); 60 | pair.write(k.as_bytes()).unwrap(); 61 | pair.push(b'='); 62 | pair.write(v.as_bytes()).unwrap(); 63 | CString::new(pair).unwrap() 64 | }).collect::>(); 65 | let mut c_env = env.iter().map(|x| x.as_ptr()).collect::>(); 66 | c_env.push(null()); 67 | unsafe { 68 | if EXEC_COMMAND_LINE != null() { 69 | transmute::<_, Box>(EXEC_COMMAND_LINE); 70 | } 71 | let new = Box::new(ExecCommandLine { 72 | program: program.to_cstring(), 73 | args: args, 74 | c_args: c_args, 75 | env: env, 76 | c_env: c_env, 77 | pid: getpid(), 78 | }); 79 | 80 | EXEC_COMMAND_LINE = &*new; 81 | forget(new); 82 | } 83 | } 84 | 85 | extern "C" fn exec_handler(sig:c_int) { 86 | unsafe { 87 | if getpid() != (*EXEC_COMMAND_LINE).pid { 88 | panic!("Early signal {:?} after fork", sig); 89 | } else { 90 | let err = execve((*EXEC_COMMAND_LINE).program.as_ptr(), 91 | (*EXEC_COMMAND_LINE).c_args.as_ptr(), 92 | (*EXEC_COMMAND_LINE).c_env.as_ptr()); 93 | panic!("Couldn't exec on signal {}, err code {}", sig, err); 94 | } 95 | } 96 | } 97 | 98 | 99 | /// Set a handler for multiple signals. If no `set_command_line` was called 100 | /// before this function the command-line is set from ``std::env`` 101 | /// 102 | /// The `avoid_race_condition` fixes race condition when one of the signals in 103 | /// set is delivered second time before the new process is able to set signal 104 | /// handler itself (most probably leading to process death). But if it's set 105 | /// to `true` process is started with another signal mask, so it should fix 106 | /// signal mask (which this function does too). 107 | /// 108 | /// In other words `avoid_race_condition=true` is useful is the same program 109 | /// is executed and it calls `set_handler` on early startup. 110 | /// 111 | /// For `avoid_race_condition=true` is also important to use single call for 112 | /// `set_handler` for all signals, because it avoids race condition between 113 | /// all combinations of subsequent signals in the set. 114 | /// 115 | /// Since version v0.3.0 command-line is executed only if pid of a process 116 | /// matches original pid where set_handler was called. I.e. you need to 117 | /// set_handler again for forked process if that is desired. 118 | pub fn set_handler(signals: &[Signal], avoid_race_condition: bool) 119 | -> nix::Result<()> 120 | { 121 | unsafe { 122 | if EXEC_COMMAND_LINE == null() { 123 | set_command_line(current_exe().unwrap(), args_os(), vars_os()); 124 | } 125 | let mut sigset = SigSet::empty(); 126 | if avoid_race_condition { 127 | for &sig in signals { 128 | sigset.add(sig); 129 | } 130 | } 131 | let mut res = Ok(()); 132 | for &sig in signals { 133 | res = res.and_then(|()| { 134 | try!(sigaction(sig, &SigAction::new( 135 | SigHandler::Handler(exec_handler), 136 | SaFlags::empty(), sigset))); 137 | Ok(()) 138 | }); 139 | } 140 | // TODO(tailhook) is this error reporting is ok? or maybe just panic? 141 | if avoid_race_condition && res.is_ok() { 142 | pthread_sigmask(SigmaskHow::SIG_UNBLOCK, Some(&sigset), None).unwrap(); 143 | } 144 | res 145 | } 146 | } 147 | -------------------------------------------------------------------------------- /src/ffi.rs: -------------------------------------------------------------------------------- 1 | use std::ffi::{CString, OsStr}; 2 | use std::os::unix::ffi::OsStrExt; 3 | 4 | pub trait ToCString { 5 | fn to_cstring(&self) -> CString; 6 | fn as_bytes(&self) -> &[u8]; 7 | } 8 | 9 | impl> ToCString for T { 10 | fn to_cstring(&self) -> CString { 11 | CString::new(self.as_ref().as_bytes()) 12 | .unwrap() 13 | } 14 | fn as_bytes(&self) -> &[u8] { 15 | self.as_ref().as_bytes() 16 | } 17 | } 18 | 19 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Signal handling library 2 | //! ======================= 3 | //! 4 | //! [Docs](https://docs.rs/signal/) | 5 | //! [Github](https://github.com/tailhook/signal/) | 6 | //! [Crate](https://crates.io/crates/signal) 7 | //! 8 | //! The library is focused on higher-level abstractions for handling signals. 9 | //! All low-level stuff should be in `nix`. 10 | //! 11 | //! Currently we have two mechanisms for handling exeptions: 12 | //! 13 | //! 1. The `exec_handler` module for replacing process with newly runned 14 | //! command designed as crash safety measure 15 | //! 2. The `Trap` mechanism that masks out signals and allows wait for them 16 | //! explicitly 17 | //! 18 | //! 19 | //! Both are specifically suited for making process supervisors. 20 | //! 21 | //! Note, masking out signals may also be achieved by trap (just don't call 22 | //! either `wait()` or `next()`) 23 | //! 24 | //! On TODO list: 25 | //! 26 | //! * `signalfd` 27 | //! 28 | //! The library tested only on linux 29 | //! 30 | #![warn(missing_docs)] 31 | #![warn(missing_debug_implementations)] 32 | 33 | extern crate libc; 34 | extern crate nix; 35 | 36 | mod ffi; 37 | pub mod exec_handler; 38 | pub mod trap; 39 | 40 | /// Signal number (reexported from nix) 41 | pub use nix::sys::signal::Signal; 42 | -------------------------------------------------------------------------------- /src/trap.rs: -------------------------------------------------------------------------------- 1 | //! Trap for handling signals synchronously 2 | //! 3 | //! It works as follows: 4 | //! 5 | //! 1. You create a trap (`Trap::trap()`), that is RAII-style guard that masks 6 | //! out signals and unignores them, preparing them for be handled when user 7 | //! wants 8 | //! 2. Use trap as iterator yielding signals or `trap.wait(timeout)` 9 | //! 10 | //! Especially useful for running (multiple) child processes simultaneously. 11 | 12 | use std::fmt; 13 | use std::mem::uninitialized; 14 | use std::ptr::null_mut; 15 | 16 | use std::time::{Instant, Duration}; 17 | use nix::sys::signal::{sigaction, SigAction, Signal, SigSet, SaFlags}; 18 | use nix::sys::signal::{pthread_sigmask, SigmaskHow, SigHandler}; 19 | use nix::errno::{Errno, errno}; 20 | use libc::{self, timespec, sigwait}; 21 | 22 | /// A RAII guard for masking out signals and waiting for them synchronously 23 | /// 24 | /// Trap temporarily replaces signal handlers to an empty handler, effectively 25 | /// activating singnals that are ignored by default. 26 | /// 27 | /// Old signal handlers are restored in `Drop` handler. 28 | pub struct Trap { 29 | oldset: SigSet, 30 | oldsigs: Vec<(Signal, SigAction)>, 31 | sigset: SigSet, 32 | } 33 | 34 | extern "C" fn empty_handler(_: libc::c_int) { } 35 | 36 | impl Trap { 37 | /// Create and activate the signal trap for specified signals. Signals not 38 | /// in list will be delivered asynchronously as always. 39 | pub fn trap(signals: &[Signal]) -> Trap { 40 | unsafe { 41 | let mut sigset = SigSet::empty(); 42 | for &sig in signals { 43 | sigset.add(sig); 44 | } 45 | let mut oldset = uninitialized(); 46 | let mut oldsigs = Vec::new(); 47 | pthread_sigmask(SigmaskHow::SIG_BLOCK, Some(&sigset), Some(&mut oldset)) 48 | .unwrap(); 49 | // Set signal handlers to an empty function, this allows ignored 50 | // signals to become pending, effectively allowing them to be 51 | // waited for. 52 | for &sig in signals { 53 | oldsigs.push((sig, sigaction(sig, 54 | &SigAction::new(SigHandler::Handler(empty_handler), 55 | SaFlags::empty(), sigset)) 56 | .unwrap())); 57 | } 58 | Trap { 59 | oldset: oldset, 60 | oldsigs: oldsigs, 61 | sigset: sigset, 62 | } 63 | } 64 | } 65 | 66 | /// Wait until any of signals arrived or timeout occurs. In case of 67 | /// timeout returns None, otherwise returns signal number. 68 | /// 69 | /// Note the argument here is a deadline, not timeout. It's easier to work 70 | /// with deadline if you call wait() function in a loop. 71 | #[cfg(target_os = "linux")] 72 | pub fn wait(&self, deadline: Instant) -> Option { 73 | use libc::sigtimedwait; 74 | 75 | loop { 76 | let now = Instant::now(); 77 | let timeout = if deadline > now { 78 | deadline.duration_since(now) 79 | } else { 80 | Duration::from_secs(0) 81 | }; 82 | let tm = timespec { 83 | tv_sec: timeout.as_secs() as libc::time_t, 84 | tv_nsec: (timeout - Duration::from_secs(timeout.as_secs())) 85 | .subsec_nanos() as libc::c_long, 86 | }; 87 | let sig = unsafe { sigtimedwait(self.sigset.as_ref(), 88 | null_mut(), &tm) }; 89 | if sig > 0 { 90 | return Some(Signal::from_c_int(sig).unwrap()); 91 | } else { 92 | match Errno::last() { 93 | Errno::EAGAIN => { 94 | return None; 95 | } 96 | Errno::EINTR => { 97 | continue; 98 | } 99 | _ => { 100 | panic!("Sigwait error: {}", errno()); 101 | } 102 | } 103 | } 104 | } 105 | } 106 | } 107 | 108 | impl Iterator for Trap { 109 | type Item = Signal; 110 | fn next(&mut self) -> Option { 111 | let mut sig: libc::c_int = 0; 112 | loop { 113 | if unsafe { sigwait(self.sigset.as_ref(), &mut sig) } == 0 { 114 | return Some(Signal::from_c_int(sig).unwrap()); 115 | } else { 116 | if Errno::last() == Errno::EINTR { 117 | continue; 118 | } 119 | panic!("Sigwait error: {}", errno()); 120 | } 121 | } 122 | } 123 | } 124 | 125 | impl Drop for Trap { 126 | fn drop(&mut self) { 127 | unsafe { 128 | for &(sig, ref sigact) in self.oldsigs.iter() { 129 | sigaction(sig, sigact).unwrap(); 130 | } 131 | pthread_sigmask(SigmaskHow::SIG_SETMASK, Some(&self.oldset), None) 132 | .unwrap(); 133 | } 134 | } 135 | } 136 | 137 | impl fmt::Debug for Trap { 138 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 139 | f.debug_struct("Trap") 140 | .finish() 141 | } 142 | } 143 | -------------------------------------------------------------------------------- /vagga.yaml: -------------------------------------------------------------------------------- 1 | commands: 2 | 3 | make: !Command 4 | description: Build library and binaries 5 | container: ubuntu 6 | run: [cargo, build] 7 | 8 | test: !Command 9 | description: Run tests 10 | container: ubuntu 11 | run: [cargo, test] 12 | 13 | cargo: !Command 14 | description: Run any cargo command 15 | container: ubuntu 16 | run: [cargo] 17 | 18 | doc: !Command 19 | description: Build documentation 20 | container: ubuntu 21 | epilog: | 22 | --------------------------------------------------------- 23 | Documentation is built under target/doc/signal/index.html 24 | run: [cargo, doc] 25 | 26 | _bulk: !Command 27 | description: Run `bulk` command (for version bookkeeping) 28 | container: ubuntu 29 | run: [bulk] 30 | 31 | containers: 32 | 33 | ubuntu: 34 | setup: 35 | - !Ubuntu bionic 36 | - !Install [ca-certificates, build-essential, vim] 37 | 38 | - !TarInstall 39 | url: "https://static.rust-lang.org/dist/rust-1.26.0-x86_64-unknown-linux-gnu.tar.gz" 40 | script: "./install.sh --prefix=/usr \ 41 | --components=rustc,rust-std-x86_64-unknown-linux-gnu,cargo" 42 | - &bulk !Tar 43 | url: "https://github.com/tailhook/bulk/releases/download/v0.4.11/bulk-v0.4.11.tar.gz" 44 | sha256: b718bb8448e726690c94d98d004bf7575f7a429106ec26ad3faf11e0fd9a7978 45 | path: / 46 | 47 | environ: 48 | HOME: /work/target 49 | --------------------------------------------------------------------------------