1#include"cache.h" 2 3/* 4 * Some cases use stdio, but want to flush after the write 5 * to get error handling (and to get better interactive 6 * behaviour - not buffering excessively). 7 * 8 * Of course, if the flush happened within the write itself, 9 * we've already lost the error code, and cannot report it any 10 * more. So we just ignore that case instead (and hope we get 11 * the right error code on the flush). 12 * 13 * If the file handle is stdout, and stdout is a file, then skip the 14 * flush entirely since it's not needed. 15 */ 16voidmaybe_flush_or_die(FILE*f,const char*desc) 17{ 18static int skip_stdout_flush = -1; 19struct stat st; 20char*cp; 21 22if(f == stdout) { 23if(skip_stdout_flush <0) { 24 cp =getenv("GIT_FLUSH"); 25if(cp) 26 skip_stdout_flush = (atoi(cp) ==0); 27else if((fstat(fileno(stdout), &st) ==0) && 28S_ISREG(st.st_mode)) 29 skip_stdout_flush =1; 30else 31 skip_stdout_flush =0; 32} 33if(skip_stdout_flush && !ferror(f)) 34return; 35} 36if(fflush(f)) { 37/* 38 * On Windows, EPIPE is returned only by the first write() 39 * after the reading end has closed its handle; subsequent 40 * write()s return EINVAL. 41 */ 42if(errno == EPIPE || errno == EINVAL) 43exit(0); 44die_errno("write failure on '%s'", desc); 45} 46} 47 48voidfsync_or_die(int fd,const char*msg) 49{ 50if(fsync(fd) <0) { 51die_errno("fsync error on '%s'", msg); 52} 53} 54 55voidwrite_or_die(int fd,const void*buf,size_t count) 56{ 57if(write_in_full(fd, buf, count) <0) { 58if(errno == EPIPE) 59exit(0); 60die_errno("write error"); 61} 62} 63 64intwrite_or_whine_pipe(int fd,const void*buf,size_t count,const char*msg) 65{ 66if(write_in_full(fd, buf, count) <0) { 67if(errno == EPIPE) 68exit(0); 69fprintf(stderr,"%s: write error (%s)\n", 70 msg,strerror(errno)); 71return0; 72} 73 74return1; 75} 76 77intwrite_or_whine(int fd,const void*buf,size_t count,const char*msg) 78{ 79if(write_in_full(fd, buf, count) <0) { 80fprintf(stderr,"%s: write error (%s)\n", 81 msg,strerror(errno)); 82return0; 83} 84 85return1; 86}