0

Ubuntu 20, Bash 5.

There is probably something silly I am overlooking! There is this C++ binary foo, which uses std::cout, printf()and puts() to do its logging.

When I run it as ./foo from the terminal, I get some output (and a segmentation fault).

When I redirect everything ./foo > log, I get only a part of the output. When I spread that ./foo 1>one 2>two then one, as expected, contains the shortened output and two contains nothing.

There is (obviously) no central logging facility, so I can't imagine how to force flushing.

What could be wrong?


$./foo
text1
text2

$./foo > log ; cat log
text1
terdon
  • 242,166
Vorac
  • 3,077

1 Answers1

0

Logging has nothing to do with it, and this is a basic facet of C and C++ programming that you need to learn.

The standard I/O library routines are fully buffering output, because the runtime library has determined that standard output is not a terminal device. If you want standard output line buffered, you turn line buffering on in code with setvbuf(), or you persuade the C runtime library that standard output is a terminal with tools like Bernstein ptybandage, or you use idiosyncratics hooks into the C library to turn on line buffering with code injection tools such as stdbuff. ptybandage is probably the best choice here. It is non-invasive and you probably do not want to have explicit buffering overrides in your program, once you actually understand the nature of standard I/O buffering.

Do not log to standard output, by the way. Log to std::clog.

Further reading

JdeBP
  • 68,745
  • 1
    can you expand a bit on what buffering has to do with it? – ilkkachu Jun 01 '20 at 11:31
  • 1
    ... I mean that it looks like they only viewed the output file after the program completed, so the buffers should be flushed by then, and there shouldn't be the same effect of delayed output as with, e.g. tail -f |grep. And if all the output goes to stdout, there's only one fd and one file position involved, so even if stdio and iostream buffer independently, they shouldn't overwrite each other, right? What am I missing? – ilkkachu Jun 01 '20 at 11:43
  • @ilkkachu the program terminates with a segmentation fault. The program is launched the same way, just with redirection one time. Is writing to a file different than to stdout? I would prefer not to change the source code and it's chaotic logging. – Vorac Jun 01 '20 at 12:47
  • 1
    @Vorac, right, if it terminates with a segmentation fault every time, then some output might be left in the buffers and not written. Maybe that's what JdeBP referred to here, not that their answer was too clear on that. Your snippets about the output in the question also don't show the segmentation fault. – ilkkachu Jun 01 '20 at 13:59