Output redirection

Conor P. Cahill cpcahil at virtech.uucp
Fri Oct 19 22:14:59 AEST 1990


In article <4859 at graphite20.UUCP> joshi at motcid.UUCP (Abhay B. Joshi) writes:
>  [ program with mixed stderr and stdout output deleted]
>
>	% a.out		# prints "Some People Are In Very Deep Trouble"
>	% a.out >tmp 2>&1
>	% cat tmp	# prints "Are In Deep Some People Very Trouble"

The problem is the way that stderr and stdout are buffered.  If going
to a tty, both of them are line buffered on most systems.  This means
that once a \n is placed into the buffer, it is flushed.

In the case of re-direction, the stderr remains line buffered while the
stdout becomes block buffered (it won't be written out until it gets
a full block of data or is flushed directly).

You can solve this problem two ways.  The first way is the turn off
the buffering of data.  This is not the best solution and can have
a detrimental effect on the performance of your system.  To do this
you need to add the following calls to the begining of your 
program:
		setbuf(stdout,(char *)0);
		setbuf(stderr,(char *)0);

The second (and optimal) way to solve the problem is to place a call to
fflush() whereever it is important.  This way you only flush the buffer
when it is necessary.


-- 
Conor P. Cahill            (703)430-9247        Virtual Technologies, Inc.,
uunet!virtech!cpcahil                           46030 Manekin Plaza, Suite 160
                                                Sterling, VA 22170 



More information about the Comp.unix.shell mailing list