r/C_Programming • • 22d ago

We can do better than line-buffered output

https://nullprogram.com/blog/2026/11/05/
52 Upvotes

41 comments sorted by

22

u/aioeu 21d ago edited 21d ago

I think glibc's literal interpretation of the standard is right here. The C standard does not say that a line buffered output stream is flushed on some newline characters, but not flushed on others. It says that it is intended to be flushed "when a new-line character is encountered". That has to be the case even if it isn't the final newline in the buffer.

A stream may be connected to something where the write syscall actually does something significant. For instance, it might be sending the data over some kind of datagram protocol; the programmer should be able to rely on the automatic buffer flushes generating separate datagrams.

1

u/8d8n4mbo28026ulk 21d ago

A stream may be connected to something where the write syscall actually does something significant. For instance, it might be sending the data over some kind of datagram protocol; the programmer should be able to rely on the automatic buffer flushes generating separate datagrams.

If you do ./a.out | less with the example program in the post, glibc does:

write(1, "a\nb\nc\n", 6)                = 6

And there's your crazy bug.

4

u/skeeto 21d ago

In ./a.out | less the output is a pipe, not a character device like a terminal, so libc ought to fully-buffer this one. This is the situation the stdbuf command is intended to address.

2

u/8d8n4mbo28026ulk 21d ago

Ah, thanks! I didn't know about stdbuf. But yeah, I saw the ioctl() in strace, which checks whether the output is a terminal. It's just another example where, I think, you shouldn't depend on how libc is going to flush things out.

4

u/aioeu 21d ago edited 21d ago

You've misinterpreted my comment.

If the programmer explicitly ensures the stream is line buffered — with setvbuf, for instance — then it would be a bug in the C library if it did not flush the buffer on each and every newline character. It doesn't matter what the stream is connected to.

This is "depending" on the C library following the standard... which is what you ought to be able to do.

1

u/8d8n4mbo28026ulk 21d ago

Ah, you're right, sorry. I forgot about setvbuf(). Still, I find that it ends up being more work than using some POSIX interface, for example. Even glibc has had correctness bugs (not sure about stdio in particular), and hand-rolling buffering isn't that many lines of code.

1

u/aioeu 21d ago edited 21d ago

Ah, you're right, sorry. I forgot about setvbuf(). Still, I find that it ends up being more work than using some POSIX interface, for example.

Err, setvbuf has been a part of standard C since ANSI C, and therefore it's been in POSIX since POSIX.1-2001.

1

u/8d8n4mbo28026ulk 21d ago

? Obviously. I mean write(), writev() and friends, which are only part of POSIX. There, pedancy restored.

3

u/theldus 21d ago

Why not both? A program can always check whether stdout is a pipe, a tty, or something else, and make the best decision based on that.

For a pipe, yes, it makes perfect sense to be line-based. If it’s strictly a tty, there might well be some optimizations possible.

If you meant that a tty can be a device, such as a serial device, then yes... but that will depend entirely on the program's nature, and etc.

7

u/aioeu 21d ago edited 21d ago

Programmers can already manage a stream's buffer. They can request one of the standard buffering modes using setvbuf, for instance. Or they can ignore the C library completely and do their own buffering, as the author of the post is doing. Programmers can make that decision based on what the stream is connected to if they want.

I am just talking about what the C library should do when it has a line-buffered stream — whether or not the programmer has asked for that explicitly. The post commented on glibc, and its author seemed a little surprised and annoyed that it took the C standard so literally. I assert that taking it literally is the only correct approach for the standard library.

1

u/greg_kennedy 21d ago

incidentally I was really pissed off when I learned that in c++, printing "\n" and printing std::endl do different things, though the latter is often recommend as the C++ way to do the former

-2

u/8d8n4mbo28026ulk 21d ago

I'd argue that's just asking for crazy bugs in the future. In those cases, just call write() directly or fflush().

10

u/aioeu 21d ago

It's only a bug if the C library doesn't follow the standard. The standard is clear.

Anyway, I'm sure this is why glibc works like this. It's certainly something you can rely on with glibc.

30

u/kinchkun 21d ago

We could poke this concurrently in a thread, awoken via futex when data is written to the buffer. 

Yeah, thanks, i think flushing on newline is fine.

8

u/skeeto 21d ago

The article suggests using neither of those options, so comparing them makes no sense.

1

u/8d8n4mbo28026ulk 21d ago

It is fine, but the point is that doing many many flushes within a short window, where a human can't possibly tell one from the next, is doing unnecessary work. I think it's an interesting perspective.

13

u/zhivago 21d ago

I can see that you have never operated at 300 baud. :)

3

u/arthurno1 21d ago

Who does it nowadays? And actually if you want something that humans can read as it is printed (30 chars a sec), then his technique with a timer would be exactly what you want.

0

u/manystripes 21d ago

Not quite that low but I've had to run 4800 baud recently on a project because the microcontroller was severely underclocked as a power saving measure and we did not want to reconfigure the core frequency and all of the peripheral prescalars just so we could debug over UART on one of the standard baud rates.

But then, we were so resource constrained we didn't even do line buffering, everything started clocking out the instant the first byte hit the UART buffer

4

u/arthurno1 21d ago

Yeah, but, that is another situation. Old terminals were like timed on purpose 300 bauds so text is readable for humans as it appears, I thought you meant something like that :). Yes, in your situation you certainly don't want to add more context switching with timers 😀.

1

u/LordRybec 21d ago

I haven't run into this yet, but I've massively underclocked microcontrollers for exactly this purpose, and as long it's fast enough to get the data where it needs to be on time, I'd be happy with well under 4800 baud.

The reality is that a lot of modern microcontroller applications waste a ton of power because they spend most of the time idling. Sure, you can sleep them, but it can be far more power efficient to just run them at a really low clock instead. I wonder if, as AI starts driving electricity prices up, large scale microcontroller users (industrial stuff, for example) might start considering doing this more to save money on power. (Sure, it's not much, but I still hear parents telling their kids to turn out the lights on the way out of the house to save power, when they are using 4 watt LED bulbs.)

0

u/SeriousPlankton2000 21d ago

At that point you just open a logfile. You probably print more than you intend the user to read.

1

u/8d8n4mbo28026ulk 21d ago

The article is literally about trying to avoid that:

Line buffering is a common bottleneck in non-interactive terminal applications such that it’s worth redirecting output to a file or pipe in order to avoid it. It doesn’t have to be this way.

Many interactive (or not) applications print in bursts, so it's still beneficial if you could buffer for a little longer to reduce expensive flushes.

1

u/SeriousPlankton2000 21d ago

Name 3 applications that do usually output more text than what can be printed during the time between you pressing enter and your ear receiving the sound of the key; and where you usually don't pipe the output through more / less anyway in these cases.

1

u/8d8n4mbo28026ulk 21d ago

grep, find and the author lists unzip too. However, this is not about winning some argument, it's about sharing an alternative little way you could do line buffering when outputting to a terminal. For the life of me I don't understand how's that so controversial.

2

u/stianhoiland 21d ago

Skill issue. (Skill: Reading comprehension.)

5

u/MarekKnapek 21d ago

I did something similar for our log file output. Before my change, there was a ton of small writes. Each opening a file, writing to it, closing it. After my change, there was an append to a shared buffer and a thread notification. On first write, the log output would go straight to the disk, just as before. Any other log outputs would wait in queue for 5 seconds or for 5 MB, whichever was filled first. Massive speedup for our app.

1

u/sphen_lee 20d ago

How did you handle flushing the buffer in the event of a crash? You don't want to lose output since the last lines of the log are usually the ones you need to diagnose the issue

21

u/trejj 21d ago

Adding nondeterministic timing specific behavior to one of the most mundane things - text output printing.. what could go wrong, when on fast machines you get behavior X, and on slow machines you get behavior Y.

Run in a VM, you get behavior X, run under contention, you get behavior Y.

That would be a hard pass for me.

10

u/skeeto 21d ago

Character device input reaching wherever it's supposed to go (screen, network, etc.) is already non-deterministic. So this adds no new non-determinism. Fully-buffered output, where determinism might matter, is unaffected.

-1

u/LordRybec 21d ago

I think line buffering is a good default. It should operate by consistent rules, like always flush on a newline. I don't think random people online having other use cases that need something else justifies changing the default.

That said, I'm disappointed that changing this behavior is a huge pain! I started out as a video game programmer in QBasic, where you could read input in line buffered chunks or as individual keycode inputs. For turn based games, line buffering was the perfect tool, and when I wanted to write real-time games, reading keycode input directly was ideal. For line buffered input you'd do something like this:

INPUT "What do you want to do?", command

The first argument is the prompt and the second is the variable to store the input. This blocks until a newline. From there you compare and do whatever it is the user indicated.

For keycode input you'd do something like this:

R$ = INKEY$

INKEY$ returns the keycode, and now you can compare R$ to find out what key the user pressed. This does not block. If the user isn't pressing a key when it runs, R$ = "", so a common pattern would be:

DO
    R$ = INKEY$
LOOP UNTIL R$ <> ""

You would only use this though, if you wanted to block. For a real-time game I would just read INKEY$ at the end of the loop, use LOOP UNTIL to check if it is CHR$(27), to bail out and end the program when ther user pressed Escape, and then the loop starts over, and keyboard input handling starts at the beginning of the loop.

This was very straightforward. I could use whichever input scheme I wanted without jumping through any hoops. I could even mix them in the same program without any side effects. Of course, there's still no non-blocking buffered input option. If you wanted non-blocking buffered input, you would have to read INKEY$ and add characters to a buffer manually as the user typed them.

---

Unfortunately in C it's a huge pain to do anything but buffered line input. Sure, as the article says, you can create new pipes, which don't block until newlines by default, and honestly, pipes aren't that difficult. Most resources trying to teach them stink, which makes them seem a lot harder than they are, but if you can find Beej's IPC guide, it teaches pipes extremely well. (In fact, I used it as the textbook for an undergrad "Concurrency and Parallelism" course. It's free, and it's better quality than any other textbook on the topic I've seen.) But this doesn't work if you want user input. Pipes are awesome for certain types of interprocess communication, but you can't inject input into them from the keyboard (outside of stdin, through the console).

There are ways of changing stdin behavior, but they are OS dependent and a pain in every OS. I use SDL2 now days when I need unbuffered real-time input. It's a game library, and when I need this, I'm usually writing a game, so it works really well. It also presents input as an event buffer, which is especially good for games and real-time applications in general. I've done some game and real-time non-game dev in Python as well, and I use Pygame in the same way. But what if I don't want a graphical application? Ncurses can do it. There's a series of functions you can call to put it into an unbuffered mode where individual input characters can be read in real-time, and there's even a function that allows arrow keys and other non-character inputs to be captured. It's kind of a pain to learn though, and portability isn't 100%.

Here's the thing: I understand that C is an old language that originated back when line input was generally the only input. It was designed with terminals in mind, and terminals themselves were often line buffered, so aligning the language to the hardware was efficient and made sense. It's clear that by the late 1980s, when QBasic started to be a thing, language designers recognized that computing was rapidly heading toward user interfaces that were not constrained to line input and needed to be able to accept input directly and immediately, rather than waiting for a specific character. But then we seem to have lost that. Visual Basic dropped INKEY$ entirely, reverting back to just line input. There's a .NET function you can call to get input like this for console applications, but that's like using SDL2 in C, not like the language itself providing that capability. Even Python doesn't have this capability built in. Sure, you can do it with Tkinter, but you have to create a window instance for the events to go to. None of this is using stdin. Your only options for that are complex OS level manipulation of stdin or ncurses which has limited portability.

This functionality should be built into the language. INKEY$ was introduced in GW-BASIC in 1983, and then it was inherited into QBasic in 1991. It was clearly already known that this was a valuable feature long before C89. Functionality either for changing input modes or for capturing input in different ways, changing modes behind the scenes as needed, should have been added in C89. And yet, it's 2026, and we still don't have it.

I don't really like most of the new features added to C since C99. There are a handful of C11 features I like, but they were part of the GNU C99 extensions long before 2011. I think the next C standard needs to add this as a standard library addition. Either there should be a function for switching modes between the default buffered, blocking until newline line input, buffered non-blocking line input, and unbuffered direct read of the most recent key pressed, or there needs to be addition functions for reading input, one that reads whatever is there without blocking, and one that gets keyboard state directly (which could include multiple keys being pressed at the same time). The current default should be left as the default, not just for backward compatibility, but also because it just makes sense, but C being stuck in the terminal era is frankly kind of dumb.

2

u/LordRybec 21d ago

setvbuf()? Is this what I'm looking for? Because I've searched many time for a portable way to do this, and I've never come across this. I've been programming in C for over 25 years now. Supposedly this was added in ANSI C89 and then added to ISO C90.

Ok, so evidently MSVC doesn't support it correctly. It only does full buffering and no buffering.

I'll have to play around with this and see how it works. There must be some reason I haven't heard of it despite spending hours on a great many occasions trying to find some way of changing input buffering modes without using non-portable OS specific code.

0

u/[deleted] 21d ago

[deleted] — view deleted comment

1

u/8d8n4mbo28026ulk 21d ago

If you do line buffering, you do a write() syscall anyway, which can be expensive if the output is a terminal, as discussed in the article. Doing a syscall to check a deadline is significantly cheaper, because it just fetches some data.

On Linux, it won't even be a syscall, it'll go through the VDSO, which is just a regular call.

1

u/arthurno1 21d ago

VDSO still taxes CPU, and as you say you are already doing heavy syscall stuff if you are in a printloop, so you don't want even on more. On the contrary, you probably wish to minimize the burden on cpu. Benchmark, that is the best way.

1

u/8d8n4mbo28026ulk 21d ago edited 21d ago

I don't understand what you're saying, sorry. It's trivially verifiable information. The author talks about unzip. If you do less flushes to the terminal (and thus buffer for longer), in a modern environment it's highly likely it'll take less overall wall time to output. I've hit this personally, too, which is why I almost always fully buffer.

you are already doing heavy syscall stuff if you are in a printloop, so you don't want even on more. On the contrary, you probably wish to minimize the burden on cpu

The point of the deadline is to minimise the (write()) syscalls, thus burden the CPU less.

1

u/arthurno1 20d ago

Benchmark, that is the best way.

I don't understand what you're saying, sorry.

It means you should make a test programs in which you measure the execution time, preferrably several times, on the exact same input data and preferrably same machine load. You can find more information here.

Here are some practical examples or for example more detailed here.

2

u/8d8n4mbo28026ulk 20d ago

I know what benchmarking is, and you've carefully avoided everything else. If you bothered to actually follow your own advice, that is, benchmark what is presented here, you'd find out that what you said makes no sense whatsoever in this context.

1

u/arthurno1 20d ago

I have read everything you say, but you are theorycrafting in my personal opinion, that is why I didn't answer the rest.

If you do less flushes

His idea was to do more flushed, that is why they want timers: if there is no new line and buffer is not full yet, they want to flush anyway. The timer is the third trigger so to say. So it is more overall flushes not less.

But without a benchmark you can't say anything. I think context switching will kill the performnce, you believe on the contrary, if you are interesting measure, that is the only way. I am not interesting enough, to spend time on measuring something I am almost certain sure would not give more performance.

2

u/8d8n4mbo28026ulk 20d ago edited 20d ago

you are theorycrafting

No! Again, I've hit this bottleneck personally. And the author talks about how he hit that himself with unzip.

His idea was to do more flushed [sic]

No, you've misunderstood. The idea is to use a deadline to buffer more and thus flush less frequently.

I think context switching will kill the performnce

Wrong. A syscall won't necessarily context switch. Secondly, we've already established that on Linux that's going through the VDSO, so just a regular function call. Thirdly, calling write() more frequently is exactly the kind of thing that would result in context switches.

I am not interesting enough, to spend time on measuring something I am almost certain sure would not give more performance.

You're theorycrafting.

1

u/arthurno1 20d ago

The idea is to use a deadline to buffer more and thus flush less frequently.

Indeed, I stand corrected, I was reading fast and glancing and in the discussion totally forgot what was the goal. My bad; I should have looked again second time. Indeed they want to flush less not more, and I checked vSDO too; it is a user-space lock. I am not sure though if the problem here is either C stdio or unzip. I think the problem is the default mode of unzip, but they are aware of it too and give -q option. Perhaps they should have chozen something else as default, and just printed themselves an indicator that progress is on the way after timeout. So it is more per-application problem than C stdio.

4

u/LordRybec 21d ago

Repeated system calls is part of why printing large amounts of debug text to the console is slow. As you say, all the context switching and such is expensive. It's always better to do as much as you can in each system call than it is to split it up between a large number of system calls, whenever possible.

Of course, if it isn't possible for the specific use case, but the high cost of the system calls isn't a problem, then you do what you have to. But I don't see a lot of cases beyond debugging where it is acceptable to slow the program down to the speed of the program that dramatically.