Xref: utzoo comp.sources.games.bugs:929 comp.sources.d:3873 alt.sources.d:20 Path: utzoo!attcan!uunet!ginosko!gem.mps.ohio-state.edu!tut.cis.ohio-state.edu!ucbvax!ucsfcgl!cca.ucsf.edu!wet!epsilon From: epsilon@wet.UUCP (Eric P. Scott) Newsgroups: comp.sources.games.bugs,comp.sources.d,alt.sources.d Subject: What setbuf() is and why you should use it Summary: A few minutes of your time will save hours of mine Keywords: curses fflush setbuf stdio Message-ID: <283@wet.UUCP> Date: 15 Jul 89 22:28:12 GMT Reply-To: epsilon@wet.UUCP (Eric P. Scott) Followup-To: comp.sources.games.bugs Organization: Wetware Diversions, San Francisco Lines: 39 Many, many screen-oriented applications posted to the net have a serious flaw: they do terminal output a character at a time. This is fine for single-user PCs running MSDOS. This is NOT fine for multi-user machines running UNIX. The culprit here is Standard I/O; stdout is not buffered when directed to a terminal. (System V has line buffering, but it's not the appropriate solution here.) This means that a write(2) call is performed for each character output. This has substantial overhead on many machines--not only does your program run slowly, response time for everyone else is degraded. The fix is very simple: put setbuf(stdout, malloc(BUFSIZ)); early in main(), and (if you've done any output) fflush(stdout); before asking for terminal input, sleeping, going heavily compute-bound, changing tty modes, or using fork/exec/system-type calls. This causes stdio to store up to BUFSIZ (defined in ) characters before demanding a context switch. Since BUFSIZ is typically 512 or 1024, this can be a substantial improvement. Make sure you have declared malloc to return the proper type for your system (either char * or void *). I urge source-group moderators to perform a cursory check before redistributing submissions. Note that the absence of setbuf/ setvbuf/setlinebuf calls does not automatically damn a program, it just means that closer inspection is needed. This issue comes up often enough that it might warrant a mention in regular monthly/quarterly postings. -=EPS=- "We haven't found a cure for people who insist on writing printf("\n"); but our efforts at rehabilitation have been largely successful."