Prevent SIGPIPE and handle signal socket

Just few notes about SIGPIPE
I was writing a simple utility in order to zip iPhone contents. Utility allows you to download zip using a normal desktop Browser (connecting the Browser to iPhone IP).
I was hitting, sometime,  a core-dump due to signal : SIGPIPE
(lldb) bt

* thread #1: tid = 0x1f03, 0x93a05c22 libsystem_kernel.dylib`mach_msg_trap + 10, stop reason = signal SIGPIPE
    frame #0: 0x93a05c22 libsystem_kernel.dylib`mach_msg_trap + 10
    frame #1: 0x93a051f6 libsystem_kernel.dylib`mach_msg + 70
    frame #2: 0x01d78a49 CoreFoundation`__CFRunLoopServiceMachPort + 185
    frame #3: 0x01d7d84b CoreFoundation`__CFRunLoopRun + 1243
    frame #4: 0x01d7cf44 CoreFoundation`CFRunLoopRunSpecific + 276
    frame #5: 0x01d7ce1b CoreFoundation`CFRunLoopRunInMode + 123
    frame #6: 0x0216a7e3 GraphicsServices`GSEventRunModal + 88
    frame #7: 0x0216a668 GraphicsServices`GSEventRun + 104
    frame #8: 0x00145ffc UIKit`UIApplicationMain + 1211
    frame #9: 0x000026ed 1ckShare`main(argc=1, argv=0xbffff380) + 141 at main.m:16
libsystem_kernel.dylib`mach_msg_trap:
0x93a05c18:  movl   $4294967265, %eax
0x93a05c1d:  calll  0x93a0949a                ; _sysenter_trap
0x93a05c22:  ret
0x93a05c23:  nop

I Know that SIGPIPE is a signal that happens when code attempts to write using a stream / pipe / socket that is closed.
SIGPIPE     n/a     Terminate     Write on a pipe with no one to read it.
(https://en.wikipedia.org/wiki/Unix_signal)

My issue is caused by the Browser that closes the tcp socket (in some cases) meanwhile the app is sending datas . In my case this signal is useless and it is an annoying event .

prevent sigpipe

So I can avoid to trap it just with SO_NOSIGPIPE in socket options (doesn’t trigger any SIGPIPE signal) :

....
<open socket useSocket >
int optval=1;
setsockopt(useSocket, SOL_SOCKET, SO_NOSIGPIPE, &optval, sizeof(int));
....

level of SO_NOSIGPIPE is SOL_SOCKET. An other option domain is IPPROTO_TCP :
setsockopt(useSocket, IPPROTO_TCP, TCP_NODELAY , &optval, sizeof(int));

SIGPIPE handle signal

Btw another way in order to ignore SIGPIPE is use :

...
signal(SIGPIPE, SIG_IGN);
...
where SIG_IGN is SIGnal IGNored but if you want to trap you can write an handler :
....
signal(SIGPIPE, kiss_this_sig);
....
void kiss_this_sig(int signum) {  <handle signal> }
Powered by WP Review

Posts