简体   繁体   English

立即将stdout重定向到fifo

[英]Redirect stdout to fifo immediately

I have, for example, ac program that prints three lines, two seconds apart, that is: 例如,我有一个ac程序打印三行,相隔两秒,即:

  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! 第二个终端在6秒后立即打印所有内容! I would like it to print the available lines immediatly. 我希望它能立即打印出可用的线路。 How can i do it? 我该怎么做?

Obs: I can't change the source code. Obs:我无法更改源代码。 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. 如果可以重新链接程序,则可以替换每次调用后刷新的printf()函数。 Or changes the startup initialization of stdout to be unbuffered—or at least line buffered. 或者将stdout的启动初始化更改为无缓冲 - 或者至少是行缓冲。

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 如果你不能改变源代码,你可能想尝试一些解决这个相关问题的方法: bash:强制exec'd进程有无缓冲的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. 使用cat只会打印文件的内容, 而不是运行它。

If it was written in bash then it would have to be set mode bit +x, which would then make it executable. 如果它是用bash编写的话那么它必须设置模式bit + x,然后才能使它成为可执行文件。 Allowing you to run it from a terminal ./script 允许您从终端./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. 不必担心语法,因为你已经声明它不是一个改变它的选项......它用C语言写的正确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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