11

I wrote the following:

#include <stdlib.h>
#include <stdio.h>
void ExecAsRoot (char* str);
int main ()
{
  printf ("Host real ip is:");
  ExecAsRoot("ip addr | grep 'state UP' -A2 | tail -n1 | awk '{print $2}' | cut -f1  -d'/'");
  return 0;
 }

void ExecAsRoot (char* str) {
  system (str);
}

My expected output is:

Host real ip is:7.17.11.29

While the actual output is:

7.17.11.29
Host real ip is:

Why is this?

dbush
  • 205,898
  • 23
  • 218
  • 273
Joel G Mathew
  • 7,561
  • 15
  • 54
  • 86

1 Answers1

12

The output of printf is being buffered because the string being printed does not contain a newline. As a result, the buffer does not get flushed until the program ends, and therefore appears after the output of the system command.

To flush the buffer, use fflush:

printf ("Host real ip is:");
fflush(stdout);
ExecAsRoot("ip addr | grep 'state UP' -A2 | tail -n1 | awk '{print $2}' | cut -f1  -d'/'");

If you want all writes to stdout to be unbuffered, you can use setvbuf to disable buffering:

setvbuf(stdout, NULL, _IONBF, 0);     // _IONBF = unbuffered

Or more simply:

setbuf(stdout, NULL);

Then all writes to stdout will appear immediately.

dbush
  • 205,898
  • 23
  • 218
  • 273