[CALUG] More I/O buffering foolishness

Jim Bauer jfbauer at comcast.net
Thu Apr 13 22:32:51 CDT 2006


On Thursday 13 April 2006 22:17, Mordechai T. Abzug wrote:
> (2) If you can modify the script/program in question, you can usually
>     have it specify no buffering or line buffering.  Perl has a "$|"
>     variable that can disable the current (ie. stdout) buffering
>     completely, or if you use FileHandle/IO::Handle, you can use
>     setvbuf() to set line buffering, or you can manually flush() after
>     each line.  C has a setvbuf(3) call, or you can manually fflush()
>     after each line.  For the sample case:
>
>     perl -le '$|=1; while (1) {print ++$a; sleep 1}'|cat
>
>     This is portable, but only works for scripts/programs for which
>     you have the source code and are willing to modify them.

If you can't modify the program but are reasonably sure it is using
the printf() family of routines and it is not statically linked and
it is not suid/sgid, then you can do something like the following.


$ cat nobuf.c
#include <stdio.h>
_init(void) {
        setlinebuf(stdout);
}
$ gcc -c nobuf.c
$ ld -shared -o nobuf.so nobuf.o

$ LD_PRELOAD=./nobuf.so prog


nobuf.c is compiled/linked as a shared object.  The LD_PRELOAD tells
the dynamic loader to load nobuf.so.  It will automatically run any
_init() routine before 'prog's main() is called.  The _init() routine
sets standard out to be line buffered.

Warning.  Doing stuff like this is not exactly portable.



More information about the lug mailing list