Skip to content

itssofluffy/SignalTrap

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

19 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

SignalTrap

Swift Swift Build Status macOS Linux License

A Swift-3/4 implementation of signal trapping (untested on Mac etc.) with support for real-time signals (Linux only).

Usage

If Swift Package Manager is used, add this package as a dependency in Package.swift,

import PackageDescription

let package = Package (
    name:  "<your-app-name>",
    dependencies: [
        .Package(url: "https://github.com/itssofluffy/SignalTrap.git", majorVersion: 0)
    ]
)

Example

import Foundation
import SignalTrap

var count = 0
var started: TimeInterval = 0

do {
    try trap(signals: Signal.allSignals) { signal in
        let runtime = Date().timeIntervalSince1970 - started

        print("received signal: \(Signal(rawValue: signal).description)")
        print("count          : \(count)")
        print("runtime        : \(runtime) seconds")

        exit(EXIT_SUCCESS)
    }

    started = Date().timeIntervalSince1970

    alarm(2) // Wait 2 seconds for the program to be killed

    while true {
        print("timestamp: \(Date().timeIntervalSince1970)")
        count += 1
              
        if (count >= 100000) {
            print("sending signal .TERM")
            try raise(signal: .TERM)
        }
    }
} catch let error as SignalTrapError {
    print(error)
} catch {
    print("an unexpected error '\(error)' has occured in the library libSignalTrap.")
}

// Or stop it yourself with cntrl+C

License

This project is released under the MIT license. See LICENSE for details.