Monday, January 31, 2005

How to avoid BROKEN PIPE errors in code (SIGPIPE)

Recently I had to struggle a lot to fix a issue generating BROKEN PIPE on a AMD64 platform, this code works on EMT64 and other 32-bit platforms but fails on AMD64. The bottom line is be really careful when you do use a fflush.
void *stream = (FILE *)......;
............
............
//To make sure the data is written to disk (HA)
if(!fflush((FILE *)stream)){
   printf("Flush failed due to %d error refer error.h\n",errno);
}
//This is really very dangerous code if you dont have a signal handler
//written for SIGPIPE (either you write a sig handler for SIGPIPE) or
//use the following code//

/*Safe Code*/
if(!fsync(fileno((FILE *)stream)))){
  printf("Sync failed due to %d error refer error.h\n",errno);
}
I found the standards guide on context of libc functions really useful
http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_05.html
Hope you will not go through the same pain....
Vamsi

No comments: