What setbuf() is and why you should use it
Eric P. Scott
epsilon at wet.UUCP
Sun Jul 16 08:28:12 AEST 1989
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
<stdio.h>) 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."
More information about the Alt.sources.d
mailing list