I am trying to ignore SIGPIPE signal that is thrown by a third party SDK I am using in my Swift application. How do I make my application ignore SIGPIPE signal globally?
The syntax is the same as in a C program:
signal(SIGPIPE, SIG_IGN)
The problem is that SIG_IGN is not defined in Swift. For C programs, it is defined
in <sys/signal.h> as
#define SIG_IGN (void (*)(int))1
but this integer to pointer conversion is not imported into Swift, so you have to define it yourself:
let SIG_IGN = CFunctionPointer<((Int32) -> Void)>(COpaquePointer(bitPattern: 1))
signal(SIGPIPE, SIG_IGN)
For Swift 2 (Xcode 7) the following should work:
typealias SigHandler = @convention(c) (Int32) -> Void
let SIG_IGN = unsafeBitCast(COpaquePointer(bitPattern: 1), SigHandler.self)
signal(SIGPIPE, SIG_IGN)
As of Swift 2.1 (Xcode 7.1), SIG_IGN is defined as a public property
and you can simply write
signal(SIGPIPE, SIG_IGN)