Home > Enterprise >  redirect stdout and stderr to different processes
redirect stdout and stderr to different processes

Time:10-24

I am testing the answer here but when I use a C program instead of bash script, I couldn't get it to work properly.

This is the C program.

// tss.c

#include <stdio.h>

int main()
{
   while (1)
   {
      fprintf(stdout, "stdout: sias\n");
      fprintf(stderr, "stderr: cias\n");
      sleep(5);
   }

   return 0;
}

This is the test result, where I only see stderr not stdout.

$ $ { tss 2>&1 1>&3 3>&- | sed -u 's/^/err: /'; } 3>&1 1>&2 | sed -u 's/^/out: /'
err: stderr: cias
err: stderr: cias

I then notice that I need to do "fflush(stdout)" in the program. But one thing I don't understand why it is not needed for stderr, and is there a way to get it to work without inserting fflush?

CodePudding user response:

I then notice that I need to do "fflush(stdout)" in the program. But one thing I don't understand why it is not needed for stderr,

stdout is buffered by default -- line buffered when it is connected to a terminal, but block buffered otherwise. Connecting the program's stdout to a pipe produces the "otherwise" case. fflush() is how you send the buffered output to the pipe before the buffer fills.

stderr is unbuffered by default. Unless you change that, output to stderr is sent to the output device immediately.

and is there a way to get it to work without inserting fflush?

Without fflush(), the output to stdout will be emitted in buffer-size chunks. If you want stdout to be unbuffered instead, like stderr, then you can achieve that with setvbuf().

  • Related