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 code to ignore a SIGPIPE signal so that you can handle it locally is: // We expect write failures to occur but we want to handle them where // the error occurs rather than in a SIGPIPE handler. signal(SIGPIPE, SIG_IGN);
A SIGPIPE is sent to a process if it tried to write to a socket that had been shutdown for writing or isn't connected (anymore). To avoid that the program ends in this case, you could either. make the process ignore SIGPIPE. #include <signal.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With