Redirecting stdout and stderr (in a program)

Conor P. Cahill cpcahil at virtech.uucp
Thu Dec 21 23:56:06 AEST 1989


In article <635 at voodoo.UUCP>, jdt at voodoo.UUCP (Jim Tomlinson) writes:
> To cut to the chase: we know stderr is unbuffered and stdout is
> buffered.  The following code segment should unbuffer stdout, or at
> least flush stdout before we fprintf "and to stderr":

 	[ example of tryint to redirect stdout/stderr deleted ]

> but /tmp/testlog looks like this after the code is run:
> 
> and to stderr.
> Printing to stdout
> 
> Why isn't the output in the proper order?  BTW, this is SGI's
> IRIX 3.2 (SYSV with BSD extensions).  Thanx for any help you
> can give me on this.

Because you are flushing a different stdio buffer.  Why don't you 
do something like the following:

#include <stdio.h>
#include <fcntl.h>
main()
{
	int	pd;
    
	close(1);
	close(2);

	pd = open("/tmp/xxx",O_CREAT|O_WRONLY,0666);
	/* I know, we need to check opens return */
	dup(pd);

	/* specify unbuffered output */
	if (setvbuf(stdout, (char *) NULL, _IONBF, 0))
	{
	    perror("setvbuff failed");
	    exit(-1);
	}
	fprintf(stdout, "Printing to stdout\n");
	fflush(stdout);
	fprintf(stderr, "and to stderr.\n");
}


-- 
+-----------------------------------------------------------------------+
| Conor P. Cahill     uunet!virtech!cpcahil      	703-430-9247	!
| Virtual Technologies Inc.,    P. O. Box 876,   Sterling, VA 22170     |
+-----------------------------------------------------------------------+



More information about the Comp.unix.questions mailing list