async-signal-0.2.8/.cargo_vcs_info.json0000644000000001360000000000100134330ustar { "git": { "sha1": "ef0cb32e652f87aa322b2ee449c24325f661dbf9" }, "path_in_vcs": "" }async-signal-0.2.8/CHANGELOG.md000064400000000000000000000013231046102023000140330ustar 00000000000000# Version 0.2.8 - Update README.md to use a working example. (#35) # Version 0.2.7 - Remove an invalid category from `Cargo.toml`. (#33) # Version 0.2.6 - Bump `windows-sys` to 0.52 and `async-io` to 3.3.0. (#27) # Version 0.2.5 - Bump `async-io` to version 2.0.0. (#25) # Version 0.2.4 - Add `LICENSE` files to this crate. (#23) # Version 0.2.3 - Remove the `signalfd` backend, as it offered little to no advantages over the pipe-based backend and it didn't catch signals sometimes. (#20) # Version 0.2.2 - Fix build error on Android. (#18) # Version 0.2.1 - Add support for the signalfd mechanism on Linux. (#5) - Add support for Windows. (#6) - Bump MSRV to 1.63. (#8) # Version 0.2.0 - Initial release async-signal-0.2.8/Cargo.lock0000644000000270650000000000100114200ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "async-io" version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8557f564c11bb72e6e82e80c2cf2b9d8377e45919597bcabf1945f8bd1759916" dependencies = [ "async-lock 2.8.0", "cfg-if", "concurrent-queue", "futures-io", "futures-lite 1.13.0", "parking", "polling", "rustix", "slab", "tracing", "waker-fn", "windows-sys 0.48.0", ] [[package]] name = "async-lock" version = "2.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "287272293e9d8c41773cec55e365490fe034813a2f172f502d6ddcf75b2f582b" dependencies = [ "event-listener 2.5.3", ] [[package]] name = "async-lock" version = "3.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ff6e472cdea888a4bd64f342f09b3f50e1886d32afe8df3d663c01140b811b18" dependencies = [ "event-listener 5.3.1", "event-listener-strategy", "pin-project-lite", ] [[package]] name = "async-signal" version = "0.2.8" dependencies = [ "async-io", "async-lock 3.4.0", "atomic-waker", "cfg-if", "fastrand", "futures-core", "futures-io", "futures-lite 2.3.0", "libc", "rustix", "signal-hook", "signal-hook-registry", "slab", "windows-sys 0.52.0", ] [[package]] name = "atomic-waker" version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" [[package]] name = "autocfg" version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" [[package]] name = "bitflags" version = "2.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "327762f6e5a765692301e5bb513e0d9fef63be86bbc14528052b1cd3e6f03e07" [[package]] name = "cfg-if" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "concurrent-queue" version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" dependencies = [ "crossbeam-utils", ] [[package]] name = "crossbeam-utils" version = "0.8.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5a22b2d63d4d1dc0b7f1b6b2747dd0088008a9be28b6ddf0b1e7d335e3037294" dependencies = [ "cfg-if", ] [[package]] name = "errno" version = "0.3.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac3e13f66a2f95e32a39eaa81f6b95d42878ca0e1db0c7543723dfe12557e860" dependencies = [ "libc", "windows-sys 0.48.0", ] [[package]] name = "event-listener" version = "2.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0" [[package]] name = "event-listener" version = "5.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6032be9bd27023a771701cc49f9f053c751055f71efb2e0ae5c15809093675ba" dependencies = [ "concurrent-queue", "parking", "pin-project-lite", ] [[package]] name = "event-listener-strategy" version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0f214dc438f977e6d4e3500aaa277f5ad94ca83fbbd9b1a15713ce2344ccc5a1" dependencies = [ "event-listener 5.3.1", "pin-project-lite", ] [[package]] name = "fastrand" version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "25cbce373ec4653f1a01a31e8a5e5ec0c622dc27ff9c4e6606eefef5cbbed4a5" [[package]] name = "futures-core" version = "0.3.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4bca583b7e26f571124fe5b7561d49cb2868d79116cfa0eefce955557c6fee8c" [[package]] name = "futures-io" version = "0.3.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4fff74096e71ed47f8e023204cfd0aa1289cd54ae5430a9523be060cdb849964" [[package]] name = "futures-lite" version = "1.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "49a9d51ce47660b1e808d3c990b4709f2f415d928835a17dfd16991515c46bce" dependencies = [ "futures-core", "pin-project-lite", ] [[package]] name = "futures-lite" version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "52527eb5074e35e9339c6b4e8d12600c7128b68fb25dcb9fa9dec18f7c25f3a5" dependencies = [ "fastrand", "futures-core", "futures-io", "parking", "pin-project-lite", ] [[package]] name = "libc" version = "0.2.149" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a08173bc88b7955d1b3145aa561539096c421ac8debde8cbc3612ec635fee29b" [[package]] name = "linux-raw-sys" version = "0.4.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da2479e8c062e40bf0066ffa0bc823de0a9368974af99c9f6df941d2c231e03f" [[package]] name = "parking" version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bb813b8af86854136c6922af0598d719255ecb2179515e6e7730d468f05c9cae" [[package]] name = "pin-project-lite" version = "0.2.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8afb450f006bf6385ca15ef45d71d2288452bc3683ce2e2cacc0d18e4be60b58" [[package]] name = "polling" version = "3.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "62a79e457c9898100b4298d57d69ec53d06f9a6ed352431ce5f377e082d2e846" dependencies = [ "cfg-if", "concurrent-queue", "pin-project-lite", "rustix", "tracing", "windows-sys 0.48.0", ] [[package]] name = "rustix" version = "0.38.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "745ecfa778e66b2b63c88a61cb36e0eea109e803b0b86bf9879fbc77c70e86ed" dependencies = [ "bitflags", "errno", "libc", "linux-raw-sys", "windows-sys 0.48.0", ] [[package]] name = "signal-hook" version = "0.3.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8621587d4798caf8eb44879d42e56b9a93ea5dcd315a6487c357130095b62801" dependencies = [ "libc", "signal-hook-registry", ] [[package]] name = "signal-hook-registry" version = "1.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d8229b473baa5980ac72ef434c4415e70c4b5e71b423043adb4ba059f89c99a1" dependencies = [ "libc", ] [[package]] name = "slab" version = "0.4.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f92a496fb766b417c996b9c5e57daf2f7ad3b0bebe1ccfca4856390e3d3bb67" dependencies = [ "autocfg", ] [[package]] name = "tracing" version = "0.1.40" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3523ab5a71916ccf420eebdf5521fcef02141234bbc0b8a49f2fdc4544364ef" dependencies = [ "pin-project-lite", "tracing-core", ] [[package]] name = "tracing-core" version = "0.1.32" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c06d3da6113f116aaee68e4d601191614c9053067f9ab7f6edbcb161237daa54" [[package]] name = "waker-fn" version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f3c4517f54858c779bbcbf228f4fca63d121bf85fbecb2dc578cdf4a39395690" [[package]] name = "windows-sys" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" dependencies = [ "windows-targets 0.48.5", ] [[package]] name = "windows-sys" version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ "windows-targets 0.52.5", ] [[package]] name = "windows-targets" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" dependencies = [ "windows_aarch64_gnullvm 0.48.5", "windows_aarch64_msvc 0.48.5", "windows_i686_gnu 0.48.5", "windows_i686_msvc 0.48.5", "windows_x86_64_gnu 0.48.5", "windows_x86_64_gnullvm 0.48.5", "windows_x86_64_msvc 0.48.5", ] [[package]] name = "windows-targets" version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6f0713a46559409d202e70e28227288446bf7841d3211583a4b53e3f6d96e7eb" dependencies = [ "windows_aarch64_gnullvm 0.52.5", "windows_aarch64_msvc 0.52.5", "windows_i686_gnu 0.52.5", "windows_i686_gnullvm", "windows_i686_msvc 0.52.5", "windows_x86_64_gnu 0.52.5", "windows_x86_64_gnullvm 0.52.5", "windows_x86_64_msvc 0.52.5", ] [[package]] name = "windows_aarch64_gnullvm" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" [[package]] name = "windows_aarch64_gnullvm" version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7088eed71e8b8dda258ecc8bac5fb1153c5cffaf2578fc8ff5d61e23578d3263" [[package]] name = "windows_aarch64_msvc" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" [[package]] name = "windows_aarch64_msvc" version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9985fd1504e250c615ca5f281c3f7a6da76213ebd5ccc9561496568a2752afb6" [[package]] name = "windows_i686_gnu" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" [[package]] name = "windows_i686_gnu" version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "88ba073cf16d5372720ec942a8ccbf61626074c6d4dd2e745299726ce8b89670" [[package]] name = "windows_i686_gnullvm" version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "87f4261229030a858f36b459e748ae97545d6f1ec60e5e0d6a3d32e0dc232ee9" [[package]] name = "windows_i686_msvc" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" [[package]] name = "windows_i686_msvc" version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "db3c2bf3d13d5b658be73463284eaf12830ac9a26a90c717b7f771dfe97487bf" [[package]] name = "windows_x86_64_gnu" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" [[package]] name = "windows_x86_64_gnu" version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e4246f76bdeff09eb48875a0fd3e2af6aada79d409d33011886d3e1581517d9" [[package]] name = "windows_x86_64_gnullvm" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" [[package]] name = "windows_x86_64_gnullvm" version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "852298e482cd67c356ddd9570386e2862b5673c85bd5f88df9ab6802b334c596" [[package]] name = "windows_x86_64_msvc" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" [[package]] name = "windows_x86_64_msvc" version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bec47e5bfd1bff0eeaf6d8b485cc1074891a197ab4225d504cb7a1ab88b02bf0" async-signal-0.2.8/Cargo.toml0000644000000036370000000000100114420ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" rust-version = "1.63" name = "async-signal" version = "0.2.8" authors = ["John Nunley "] exclude = ["/.*"] description = "Async signal handling" readme = "README.md" keywords = [ "async", "signal", "signal-hook", "signal-hook-registry", ] categories = [ "asynchronous", "concurrency", "os", ] license = "Apache-2.0 OR MIT" repository = "https://github.com/smol-rs/async-signal" [dependencies.cfg-if] version = "1.0.0" [dependencies.futures-core] version = "0.3.26" [dev-dependencies.async-io] version = "2.0.0" [dev-dependencies.fastrand] version = "2.0.1" [dev-dependencies.futures-lite] version = "2.3.0" [dev-dependencies.signal-hook] version = "0.3.14" [target."cfg(unix)".dependencies.async-io] version = "2.0.0" [target."cfg(unix)".dependencies.futures-io] version = "0.3.26" [target."cfg(unix)".dependencies.rustix] version = "0.38.15" features = [ "process", "std", ] default-features = false [target."cfg(unix)".dependencies.signal-hook-registry] version = "1.4.0" [target."cfg(unix)".dev-dependencies.libc] version = "0.2.139" [target."cfg(windows)".dependencies.async-lock] version = "3.3.0" [target."cfg(windows)".dependencies.atomic-waker] version = "1.1.1" [target."cfg(windows)".dependencies.slab] version = "0.4.8" [target."cfg(windows)".dependencies.windows-sys] version = "0.52" features = [ "Win32_Foundation", "Win32_System_Console", ] default-features = false async-signal-0.2.8/Cargo.toml.orig000064400000000000000000000020511046102023000151100ustar 00000000000000[package] name = "async-signal" version = "0.2.8" edition = "2018" authors = ["John Nunley "] rust-version = "1.63" description = "Async signal handling" license = "Apache-2.0 OR MIT" repository = "https://github.com/smol-rs/async-signal" keywords = ["async", "signal", "signal-hook", "signal-hook-registry"] categories = ["asynchronous", "concurrency", "os"] exclude = ["/.*"] [dependencies] cfg-if = "1.0.0" futures-core = "0.3.26" [target.'cfg(unix)'.dependencies] async-io = "2.0.0" futures-io = "0.3.26" rustix = { version = "0.38.15", default-features = false, features = ["process", "std"] } signal-hook-registry = "1.4.0" [target.'cfg(windows)'.dependencies] async-lock = "3.3.0" atomic-waker = "1.1.1" slab = "0.4.8" [target.'cfg(windows)'.dependencies.windows-sys] version = "0.52" default-features = false features = [ "Win32_Foundation", "Win32_System_Console", ] [dev-dependencies] async-io = "2.0.0" fastrand = "2.0.1" futures-lite = "2.3.0" signal-hook = "0.3.14" [target.'cfg(unix)'.dev-dependencies] libc = "0.2.139" async-signal-0.2.8/LICENSE-APACHE000064400000000000000000000251371046102023000141570ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. async-signal-0.2.8/LICENSE-MIT000064400000000000000000000017771046102023000136730ustar 00000000000000Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. async-signal-0.2.8/README.md000064400000000000000000000051301046102023000135010ustar 00000000000000# async-signal [![Build](https://github.com/smol-rs/async-signal/workflows/Build%20and%20test/badge.svg)]( https://github.com/smol-rs/async-signal/actions) [![License](https://img.shields.io/badge/license-Apache--2.0_OR_MIT-blue.svg)]( https://github.com/smol-rs/async-signal) [![Cargo](https://img.shields.io/crates/v/async-signal.svg)]( https://crates.io/crates/async-signal) [![Documentation](https://docs.rs/async-signal/badge.svg)]( https://docs.rs/async-signal) Asynchronous signal handling. This crate provides the [`Signals`] type, which can be used to listen for POSIX signals asynchronously. It can be seen as an asynchronous version of [`signal_hook::iterator::Signals`]. [`Signals`]: https://docs.rs/async-signal/latest/async_signal/struct.Signals.html [`signal_hook::iterator::Signals`]: https://docs.rs/signal-hook/latest/signal_hook/iterator/struct.Signals.html # Implementation On `unix`, this crate uses the [`signal_hook_registry`] crate to register a listener for each signal. That listener will then send a message through a Unix socket to the [`Signals`] type, which will receive it and notify the user. Asynchronous notification is done through the [`async-io`] crate. Note that the internal pipe has a limited capacity. Once it has reached capacity, additional signals will be dropped. On Windows, a different implementation that only supports `SIGINT` is used. This implementation uses a channel to notify the user. [`signal_hook_registry`]: https://crates.io/crates/signal-hook-registry [`async-io`]: https://crates.io/crates/async-io # Examples ```rust use async_signal::{Signal, Signals}; use futures_lite::prelude::*; use signal_hook::low_level; // Register the signals we want to receive. let mut signals = Signals::new(&[ Signal::Term, Signal::Quit, Signal::Int, ])?; // Wait for a signal to be received. while let Some(signal) = signals.next().await { // Print the signal. eprintln!("Received signal {:?}", signal); // After printing it, do whatever the signal was supposed to do in the first place. low_level::emulate_default_handler(signal.unwrap() as i32).unwrap(); } ``` ## License Licensed under either of * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) at your option. #### Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. async-signal-0.2.8/examples/print.rs000064400000000000000000000021551046102023000155460ustar 00000000000000// Inspired by https://github.com/vorner/signal-hook/blob/3473f4520a710f05d352275731100807196de519/examples/print.rs use async_signal::{Signal, Signals}; use futures_lite::prelude::*; use signal_hook::low_level; fn main() -> Result<(), Box> { async_io::block_on(async { // Register the signals we want to receive. #[cfg(unix)] let signals = Signals::new([ Signal::Term, Signal::Quit, Signal::Int, Signal::Tstp, Signal::Winch, Signal::Hup, Signal::Child, Signal::Cont, ])?; #[cfg(windows)] let signals = Signals::new([Signal::Int])?; // Loop over the signals. signals .for_each(|signal| { // Print the signal. eprintln!("Received signal {:?}", signal); // After printing it, do whatever the signal was supposed to do in the first place. low_level::emulate_default_handler(signal.unwrap() as i32).unwrap(); }) .await; Ok(()) }) } async-signal-0.2.8/src/channel.rs000064400000000000000000000054311046102023000147730ustar 00000000000000//! A signal notifier that uses an asynchronous channel. //! //! This is only valid for Windows, where there are less strict signal handling //! requirements. use crate::Signal; use atomic_waker::AtomicWaker; use std::io; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; use std::task::{Context, Poll}; /// The notifier that uses an asynchronous channel. #[derive(Debug)] pub struct Notifier { /// The pipe used to send signals. pipe: Arc, } impl Notifier { /// Create a new signal notifier. pub(super) fn new() -> io::Result { Ok(Self { pipe: Arc::new(Pipe { count: AtomicUsize::new(0), waker: AtomicWaker::new(), }), }) } /// Add a signal to the notifier. /// /// Returns a closure to be passed to signal-hook. pub(super) fn add_signal( &mut self, _signal: Signal, ) -> io::Result { let pipe = self.pipe.clone(); Ok(move || { pipe.push(); }) } /// Remove a signal from the notifier. pub(super) fn remove_signal(&mut self, _signal: Signal) -> io::Result<()> { Ok(()) } /// Get the next signal. pub(super) fn poll_next(&self, cx: &mut Context<'_>) -> Poll> { let mut count = self.pipe.count.load(Ordering::SeqCst); let mut registered = false; loop { // If the count is greater than zero, then we have a signal. if count > 0 { // Decrement the count. let new_count = count - 1; if let Err(new_count) = self.pipe.count.compare_exchange( count, new_count, Ordering::SeqCst, Ordering::SeqCst, ) { count = new_count; continue; } // Return the signal. return Poll::Ready(Ok(Signal::Int)); } // If the count is zero, then we need to wait for a signal. if registered { // We are already registered, so we need to wait for a signal. return Poll::Pending; } else { registered = true; self.pipe.waker.register(cx.waker()); // Try again. count = self.pipe.count.load(Ordering::SeqCst); } } } } #[derive(Debug)] struct Pipe { /// The number of SIGINT signals received. count: AtomicUsize, /// The waker to wake up. waker: AtomicWaker, } impl Pipe { /// Add a signal to the notifier. fn push(&self) { self.count.fetch_add(1, Ordering::SeqCst); self.waker.wake(); } } async-signal-0.2.8/src/lib.rs000064400000000000000000000302501046102023000141260ustar 00000000000000//! Asynchronous signal handling. //! //! This crate provides the [`Signals`] type, which can be used to listen for POSIX signals asynchronously. //! It can be seen as an asynchronous version of [`signal_hook::iterator::Signals`]. //! //! [`signal_hook::iterator::Signals`]: https://docs.rs/signal-hook/latest/signal_hook/iterator/struct.Signals.html //! //! # Implementation //! //! This crate uses the [`signal_hook_registry`] crate to register a listener for each signal. That //! listener will then send a message through a Unix socket to the [`Signals`] type, which will //! receive it and notify the user. Asynchronous notification is done through the [`async-io`] crate. //! //! Note that the internal pipe has a limited capacity. Once it has reached capacity, additional //! signals will be dropped. //! //! On Windows, a different implementation that only supports `SIGINT` is used. This implementation //! uses a channel to notify the user. //! //! [`signal_hook_registry`]: https://crates.io/crates/signal-hook-registry //! [`async-io`]: https://crates.io/crates/async-io //! //! # Examples //! //! ```no_run //! use async_signal::{Signal, Signals}; //! use futures_lite::prelude::*; //! use signal_hook::low_level; //! //! # fn main() -> Result<(), Box> { //! # async_io::block_on(async { //! // Register the signals we want to receive. //! let mut signals = Signals::new(&[ //! Signal::Term, //! Signal::Quit, //! Signal::Int, //! ])?; //! //! // Wait for a signal to be received. //! while let Some(signal) = signals.next().await { //! // Print the signal. //! eprintln!("Received signal {:?}", signal); //! //! // After printing it, do whatever the signal was supposed to do in the first place. //! low_level::emulate_default_handler(signal.unwrap() as i32).unwrap(); //! } //! # Ok(()) //! # }) //! # } //! ``` #![doc( html_favicon_url = "https://raw.githubusercontent.com/smol-rs/smol/master/assets/images/logo_fullsize_transparent.png" )] #![doc( html_logo_url = "https://raw.githubusercontent.com/smol-rs/smol/master/assets/images/logo_fullsize_transparent.png" )] cfg_if::cfg_if! { if #[cfg(windows)] { mod channel; use channel as sys; } else { mod pipe; use pipe as sys; } } cfg_if::cfg_if! { if #[cfg(unix)] { use signal_hook_registry as registry; } else if #[cfg(windows)] { mod windows_registry; use windows_registry as registry; } } use futures_core::ready; use futures_core::stream::Stream; use registry::SigId; use std::borrow::Borrow; use std::collections::HashMap; use std::fmt; use std::io; use std::pin::Pin; use std::task::{Context, Poll}; #[cfg(unix)] use std::os::unix::io::{AsFd, AsRawFd, BorrowedFd, RawFd}; mod signum { pub(crate) use std::os::raw::c_int; macro_rules! sig { ($rustix_name:ident, $raw_value:literal) => {{ #[cfg(unix)] { rustix::process::Signal::$rustix_name as c_int } #[cfg(windows)] { $raw_value } }}; } // Define these ourselves. pub const SIGHUP: c_int = sig!(Hup, 1); pub const SIGINT: c_int = sig!(Int, 2); pub const SIGQUIT: c_int = sig!(Quit, 3); pub const SIGILL: c_int = sig!(Ill, 4); pub const SIGTRAP: c_int = sig!(Trap, 5); pub const SIGABRT: c_int = sig!(Abort, 6); pub const SIGFPE: c_int = sig!(Fpe, 8); pub const SIGKILL: c_int = sig!(Kill, 9); pub const SIGSEGV: c_int = sig!(Segv, 11); pub const SIGPIPE: c_int = sig!(Pipe, 13); pub const SIGALRM: c_int = sig!(Alarm, 14); pub const SIGTERM: c_int = sig!(Term, 15); pub const SIGTTIN: c_int = sig!(Ttin, 21); pub const SIGTTOU: c_int = sig!(Ttou, 22); pub const SIGXCPU: c_int = sig!(Xcpu, 24); pub const SIGXFSZ: c_int = sig!(Xfsz, 25); pub const SIGVTALRM: c_int = sig!(Vtalarm, 26); pub const SIGPROF: c_int = sig!(Prof, 27); pub const SIGWINCH: c_int = sig!(Winch, 28); pub const SIGCHLD: c_int = sig!(Child, 17); pub const SIGBUS: c_int = sig!(Bus, 7); pub const SIGUSR1: c_int = sig!(Usr1, 10); pub const SIGUSR2: c_int = sig!(Usr2, 12); pub const SIGCONT: c_int = sig!(Cont, 18); pub const SIGSTOP: c_int = sig!(Stop, 19); pub const SIGTSTP: c_int = sig!(Tstp, 20); pub const SIGURG: c_int = sig!(Urg, 23); pub const SIGIO: c_int = sig!(Io, 29); pub const SIGSYS: c_int = sig!(Sys, 31); } macro_rules! define_signal_enum { ( $(#[$outer:meta])* pub enum Signal { $( $(#[$inner:meta])* $name:ident = $value:ident, )* } ) => { $(#[$outer])* #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash)] #[repr(i32)] pub enum Signal { $( $(#[$inner])* $name = signum::$value, )* } impl Signal { /// Returns the signal number. fn number(self) -> std::os::raw::c_int { match self { $( Signal::$name => signum::$value, )* } } /// Parse a signal from its number. #[cfg(unix)] fn from_number(number: std::os::raw::c_int) -> Option { match number { $( signum::$value => Some(Signal::$name), )* _ => None, } } } } } define_signal_enum! { // Copied from https://github.com/bytecodealliance/rustix/blob/main/src/backend/linux_raw/process/types.rs#L81-L161 /// The signal types that we are able to listen for. pub enum Signal { /// `SIGHUP` Hup = SIGHUP, /// `SIGINT` Int = SIGINT, /// `SIGQUIT` Quit = SIGQUIT, /// `SIGILL` Ill = SIGILL, /// `SIGTRAP` Trap = SIGTRAP, /// `SIGABRT`, aka `SIGIOT` #[doc(alias = "Iot")] #[doc(alias = "Abrt")] Abort = SIGABRT, /// `SIGBUS` Bus = SIGBUS, /// `SIGFPE` Fpe = SIGFPE, /// `SIGKILL` Kill = SIGKILL, /// `SIGUSR1` Usr1 = SIGUSR1, /// `SIGSEGV` Segv = SIGSEGV, /// `SIGUSR2` Usr2 = SIGUSR2, /// `SIGPIPE` Pipe = SIGPIPE, /// `SIGALRM` #[doc(alias = "Alrm")] Alarm = SIGALRM, /// `SIGTERM` Term = SIGTERM, /// `SIGCHLD` #[doc(alias = "Chld")] Child = SIGCHLD, /// `SIGCONT` Cont = SIGCONT, /// `SIGSTOP` Stop = SIGSTOP, /// `SIGTSTP` Tstp = SIGTSTP, /// `SIGTTIN` Ttin = SIGTTIN, /// `SIGTTOU` Ttou = SIGTTOU, /// `SIGURG` Urg = SIGURG, /// `SIGXCPU` Xcpu = SIGXCPU, /// `SIGXFSZ` Xfsz = SIGXFSZ, /// `SIGVTALRM` #[doc(alias = "Vtalrm")] Vtalarm = SIGVTALRM, /// `SIGPROF` Prof = SIGPROF, /// `SIGWINCH` Winch = SIGWINCH, /// `SIGIO`, aka `SIGPOLL` #[doc(alias = "Poll")] Io = SIGIO, /// `SIGSYS`, aka `SIGUNUSED` #[doc(alias = "Unused")] Sys = SIGSYS, } } /// Wait for a specific set of signals. /// /// See the [module-level documentation](index.html) for more details. pub struct Signals { /// The strategy used to read the signals. notifier: sys::Notifier, /// The map between signal numbers and signal IDs. signal_ids: HashMap, } impl Drop for Signals { fn drop(&mut self) { for signal in self.signal_ids.values() { registry::unregister(*signal); } } } impl fmt::Debug for Signals { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { struct RegisteredSignals<'a>(&'a HashMap); impl fmt::Debug for RegisteredSignals<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_set().entries(self.0.keys()).finish() } } f.debug_struct("Signals") .field("notifier", &self.notifier) .field("signal_ids", &RegisteredSignals(&self.signal_ids)) .finish() } } impl Signals { /// Create a new `Signals` instance with a set of signals. pub fn new(signals: impl IntoIterator) -> io::Result where B: Borrow, { let mut this = Self { notifier: sys::Notifier::new()?, signal_ids: HashMap::new(), }; // Add the signals to the set of signals to wait for. this.add_signals(signals)?; Ok(this) } /// Add signals to the set of signals to wait for. /// /// One signal cannot be added twice. If a signal that has already been added is passed to this /// method, it will be ignored. /// /// Registering a signal prevents the default behavior of that signal from occurring. For /// example, if you register `SIGINT`, pressing `Ctrl+C` will no longer terminate the process. /// To run the default signal handler, use [`signal_hook::low_level::emulate_default_handler`] /// instead. /// /// [`signal_hook::low_level::emulate_default_handler`]: https://docs.rs/signal-hook/latest/signal_hook/low_level/fn.emulate_default_handler.html pub fn add_signals(&mut self, signals: impl IntoIterator) -> io::Result<()> where B: Borrow, { for signal in signals { let signal = signal.borrow(); // If we've already registered this signal, skip it. if self.signal_ids.contains_key(signal) { continue; } // Get the closure to call when the signal is received. let closure = self.notifier.add_signal(*signal)?; let id = unsafe { // SAFETY: Closure is guaranteed to be signal-safe. registry::register(signal.number(), closure)? }; // Add the signal ID to the map. self.signal_ids.insert(*signal, id); } Ok(()) } /// Remove signals from the set of signals to wait for. /// /// This function can be used to opt out of listening to signals previously registered via /// [`add_signals`](Self::add_signals) or [`new`](Self::new). If a signal that has not been /// registered is passed to this method, it will be ignored. pub fn remove_signals(&mut self, signals: impl IntoIterator) -> io::Result<()> where B: Borrow, { for signal in signals { let signal = signal.borrow(); // If we haven't registered this signal, skip it. let id = match self.signal_ids.remove(signal) { Some(id) => id, None => continue, }; // Remove the signal from the notifier. self.notifier.remove_signal(*signal)?; // Use `signal-hook-registry` to unregister the signal. registry::unregister(id); } Ok(()) } } #[cfg(unix)] impl AsRawFd for Signals { fn as_raw_fd(&self) -> RawFd { self.notifier.as_raw_fd() } } #[cfg(unix)] impl AsFd for Signals { fn as_fd(&self) -> BorrowedFd<'_> { self.notifier.as_fd() } } impl Unpin for Signals {} impl Stream for Signals { type Item = io::Result; #[inline] fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { Pin::new(&mut &*self).poll_next(cx) } #[inline] fn size_hint(&self) -> (usize, Option) { // This stream is expected to never end. (std::usize::MAX, None) } } impl Stream for &Signals { type Item = io::Result; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { let signal = ready!(self.notifier.poll_next(cx))?; Poll::Ready(Some(Ok(signal))) } #[inline] fn size_hint(&self) -> (usize, Option) { // This stream is expected to never end. (std::usize::MAX, None) } } async-signal-0.2.8/src/pipe.rs000064400000000000000000000056241046102023000143240ustar 00000000000000//! A signal notifier that uses an asynchronous pipe. use crate::Signal; use async_io::Async; use futures_core::ready; use futures_io::AsyncRead; use std::io::{self, prelude::*}; use std::mem; use std::os::unix::io::{AsFd, AsRawFd, BorrowedFd, RawFd}; use std::os::unix::net::UnixStream; use std::pin::Pin; use std::task::{Context, Poll}; const BUFFER_LEN: usize = mem::size_of::(); /// The notifier that uses an asynchronous pipe. #[derive(Debug)] pub(super) struct Notifier { /// The read end of the signal pipe. read: Async, /// The write end of the signal pipe. write: UnixStream, } impl Notifier { /// Create a new signal notifier. pub(super) fn new() -> io::Result { let (read, write) = UnixStream::pair()?; let read = Async::new(read)?; write.set_nonblocking(true)?; Ok(Self { read, write }) } /// Add a signal to the notifier. /// /// Returns a closure to be passed to signal-hook. pub(super) fn add_signal( &mut self, signal: Signal, ) -> io::Result { let number = signal.number(); let write = self.write.try_clone()?; Ok(move || { // SAFETY: to_ne_bytes() and write() are both signal safe. let bytes = number.to_ne_bytes(); let _ = (&write).write(&bytes); }) } /// Remove a signal from the notifier. pub(super) fn remove_signal(&mut self, _signal: Signal) -> io::Result<()> { Ok(()) } /// Get the next signal. pub(super) fn poll_next(&self, cx: &mut Context<'_>) -> Poll> { let mut buffer = [0; BUFFER_LEN]; let mut buffer_len = 0; // Read into the buffer. loop { if buffer_len >= BUFFER_LEN { break; } // Try to fill up the entire buffer. let buf_range = buffer_len..BUFFER_LEN; let res = ready!(Pin::new(&mut &self.read).poll_read(cx, &mut buffer[buf_range])); match res { Ok(0) => return Poll::Ready(Err(io::Error::from(io::ErrorKind::UnexpectedEof))), Ok(n) => buffer_len += n, Err(e) => return Poll::Ready(Err(e)), } } // Convert the buffer into a signal number. let number = std::os::raw::c_int::from_ne_bytes(buffer); // Convert the signal number into a signal. let signal = match Signal::from_number(number) { Some(signal) => signal, None => return Poll::Ready(Err(io::Error::from(io::ErrorKind::InvalidData))), }; // Return the signal. Poll::Ready(Ok(signal)) } } impl AsRawFd for Notifier { fn as_raw_fd(&self) -> RawFd { self.read.as_raw_fd() } } impl AsFd for Notifier { fn as_fd(&self) -> BorrowedFd<'_> { self.read.as_fd() } } async-signal-0.2.8/src/windows_registry.rs000064400000000000000000000124131046102023000170030ustar 00000000000000//! Signal registration for Windows. //! //! Windows on its own does not have a concept of signals; signal handling is instead done by the //! Windows CRT, which Rust does not typically interact with. `signal-hook-registry` works by //! interfacing with the CRT, which I'd argue is somewhat of an anti-pattern in Rust. Instead, //! for this crate, let's take a look at the signals that Windows does have and how we can //! leverage them without the CRT. //! //! The six signals that Windows defines are SIGINT, SIGTERM, SIGABRT, SIGILL, SIGSEGV, and //! SIGFPE. The CRT will return an error if you try to use any other signals. Of these six, only //! SIGINT is usable for real life purposes. //! //! - SIGILL, SIGSEGV and SIGFPE are serious errors that are intended to crash the program. Users who //! listen for this signals will need to often run raw C functions (`longjmp`, direct address //! manipulation, etc etc) to accurately handle these signals. In other words, these aren't something //! that can really be handled using our `async` strategy! //! - SIGABRT is internal to the CRT and is only raised when `libc::abort()` is called. This makes it //! somewhat of a futile exercise to listen for it in Rust, since `std::process::abort()` will //! not raise `SIGABRT` and will just abort the process directly. //! - SIGTERM is never actually raised by Windows outside of the `libc::raise()` function. //! - SIGINT corresponds to the `CTRL_C_EVENT` event handled by the `SetConsoleCtrlHandler` function. //! This is probably also the only signal that is actually useful to listen for. //! //! Therefore, all we need to do to properly handle signals on Windows is to just listen for the //! `CTRL_C_EVENT` event. This is done by calling `SetConsoleCtrlHandler` with a callback function //! that iterates through a linked list of registered callbacks and calls them. use async_lock::OnceCell; use slab::Slab; use windows_sys::Win32::Foundation::BOOL; use windows_sys::Win32::System::Console::{SetConsoleCtrlHandler, CTRL_C_EVENT}; use std::io::Result; use std::mem; use std::os::raw::c_int; use std::sync::Mutex; use super::signum::SIGINT; /// The ID of a signal handler. pub(crate) type SigId = usize; /// Register a handler into the global registry. /// /// # Safety /// /// This function is safe; it is only unsafe for consistency. pub(crate) unsafe fn register( signal: c_int, handler: impl Fn() + Send + Sync + 'static, ) -> Result { // If this signal isn't SIGINT, then we can't register it. if signal != SIGINT { return Err(std::io::Error::new( std::io::ErrorKind::Other, "unsupported signal", )); } // Register the handler into the global registry. Ok(Registry::get()?.register(handler)) } /// Deregister a handler from the global registry. pub fn unregister(id: SigId) { if let Ok(registry) = Registry::get() { registry.unregister(id) } } /// The global registry of signal handlers. struct Registry { /// The list of signal handlers. handlers: Mutex>, } /// A closure that handles a signal. type Handler = Box; impl Registry { /// Get the global instance of the registry. fn get() -> Result<&'static Self> { static REGISTRY: OnceCell = OnceCell::new(); REGISTRY.get_or_try_init_blocking(|| { // Register ourselves into the global registry. let res = unsafe { SetConsoleCtrlHandler(Some(Self::handle_event), true as _) }; if res == 0 { return Err(std::io::Error::last_os_error()); } Ok(Registry { handlers: Mutex::new(Slab::new()), }) }) } /// Handle a console control event. unsafe extern "system" fn handle_event(event: u32) -> BOOL { // Make sure panics aren't transmitted across the FFI boundary. struct AbortOnDrop; impl Drop for AbortOnDrop { fn drop(&mut self) { std::process::abort(); } } let _abort_on_drop = AbortOnDrop; // If the event is CTRL_C_EVENT, then we should handle it. if event == CTRL_C_EVENT { // Get the global registry. let registry = match Self::get() { Ok(registry) => registry, Err(_) => return false as BOOL, }; // Note that Windows runs these handlers in another thread, so there's no need to // worry about async signal safety. let handlers = registry.handlers.lock().unwrap_or_else(|e| e.into_inner()); for handler in handlers.iter() { (handler.1)(); } mem::forget(_abort_on_drop); return true as BOOL; } mem::forget(_abort_on_drop); false as BOOL } /// Register a handler for a signal. fn register(&self, handler: impl Fn() + Send + Sync + 'static) -> usize { self.handlers .lock() .unwrap_or_else(|e| e.into_inner()) .insert(Box::new(handler)) } /// Unregister a handler for a signal. fn unregister(&self, id: usize) { self.handlers .lock() .unwrap_or_else(|e| e.into_inner()) .try_remove(id); } } async-signal-0.2.8/tests/sigint.rs000064400000000000000000000014151046102023000152310ustar 00000000000000use async_signal::{Signal, Signals}; use futures_lite::{future, prelude::*}; /// Send SIGINT to the current process. #[cfg(unix)] fn sigint() { unsafe { libc::raise(libc::SIGINT); } } /// Send SIGINT to the current process. #[cfg(windows)] fn sigint() { unsafe { windows_sys::Win32::System::Console::GenerateConsoleCtrlEvent( windows_sys::Win32::System::Console::CTRL_C_EVENT, 0, ); } } #[test] fn test_sigint() { future::block_on(async { let mut signals = Signals::new(Some(Signal::Int)).unwrap(); let mut next = signals.next(); assert!(future::poll_once(&mut next).await.is_none()); sigint(); assert_eq!(signals.next().await.unwrap().unwrap(), Signal::Int); }); } async-signal-0.2.8/tests/unix_signals.rs000064400000000000000000000027651046102023000164500ustar 00000000000000#![cfg(unix)] use async_signal::{Signal, Signals}; use futures_lite::{future, prelude::*}; #[test] fn endurance() { let user_signals = [Signal::Usr1, Signal::Usr2]; future::block_on(async { let mut signals = Signals::new(user_signals).unwrap(); for &signal in user_signals.iter().cycle().take(100_000) { let mut next = signals.next(); assert!(future::poll_once(&mut next).await.is_none()); unsafe { libc::raise(signal as libc::c_int); } assert_eq!( future::poll_once(&mut next) .await .unwrap() .unwrap() .unwrap(), signal ); } }); } #[test] fn distanced() { let mut signals = Signals::new(Some(Signal::Alarm)).unwrap(); std::thread::spawn(|| { future::block_on(async { let mut rng = fastrand::Rng::new(); for _ in 0..1_000 { unsafe { libc::raise(Signal::Alarm as libc::c_int); } if rng.bool() { async_io::Timer::after(std::time::Duration::from_millis(rng.u64(1..5))).await; } } }); }); future::block_on(async { for _ in 0..1_000 { assert_eq!(signals.next().await.unwrap().unwrap(), Signal::Alarm); } assert!(future::poll_once(signals.next()).await.is_none()); }); }