简体   繁体   中英

Redirect stdout to fifo immediately

I have, for example, ac program that prints three lines, two seconds apart, that is:

  printf("Wait 2 seconds...\n");
  sleep(2);
  printf("Two more\n");
  sleep(2);
  printf("Quitting in 2 seconds...\n");
  sleep(2);

I execute the program and redirect it to a pipe:

./printer > myPipe

On another terminal

cat < myPipe

The second terminal prints all at once, 6 seconds later! I would like it to print the available lines immediatly. How can i do it?

Obs: I can't change the source code. It's actually the output of a boardgame algorithm, i have to get it immediatly so that i can plug it into another algorithm, get the answer back and plug into the first one...

Change the program to this approach:

  printf("Wait 2 seconds...\n");
  fflush (stdout);
  sleep(2);
  printf("Two more\n");
  fflush (stdout);
  sleep(2);
  printf("Quitting in 2 seconds...\n");
  fflush (stdout);
  sleep(2);

Additional:

If you can't change the program, there really is no way to affect the program's built-in buffering without hacking it.

If you can relink the program, you could substitute a printf() function which flushes after each call. Or changes the startup initialization of stdout to be unbuffered—or at least line buffered.

If you can't change the source, you might want to try some of the solutions to this related question: bash: force exec'd process to have unbuffered stdout

Basically, you have to make the OS execute this program interactively.

I'm assuming that the actual source file is complete. If so, then you have to compile the source and run it to get it to do anything. Using cat will just print the contents of the file, not run it.

If it was written in bash then it would have to be set mode bit +x, which would then make it executable. Allowing you to run it from a terminal ./script

No need to worry about the syntax since you've stated it's not an option to change it and... It's correctly written in C.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM