Flash Notes

Command interpreter - Redirection of standard output and standard error


• How to display messages on stdout and stderr from a C program ?

Solution

Use printf() and fprintf()

Program

/* Program out_err.c */

#include <stdio.h>

int main()
{
printf("STDOUT\n");
fprintf(stderr, "STDERR\n");
return 0;
}

Example 1

$ out_err
STDOUT
STDERR

• How to redirect stdout and stderr to separate files ?

Solution

Use > and 2>

Example 1

$ out_err > /tmp/out 2> /tmp/err
$ cat /tmp/out
STDOUT
$ cat /tmp/err
STDERR

• How to redirect stdout and stderr to the same file ?

Solution

Use > and then 2>&1

Example 1

$ out_err > /tmp/out_err.out 2>&1
$ cat /tmp/out_err.out 
STDERR
STDOUT

• How to get stdout and stderr messages appear in the same order on screen and in the redirection file ?

Solution

Use setvbuf() in the C program

Program

/* Program out_err_nbuf.c */

#include <stdio.h>

int main()
{
setvbuf(stdout, (char *) 0, _IONBF, 0);

printf("STDOUT\n");
fprintf(stderr, "STDERR\n");
return 0;
}

Example 1

$ out_err_nbuf > /tmp/out_err_nbuf.out 2>&1
$ cat /tmp/out_err_nbuf.out 
STDOUT
STDERR