Intro To 'stdbuf' Command In Linux
2023-07-05 - By Robert Elder
I use the 'stdbuf' command to change the buffering behaviour of standard input and output:
stdbuf -o0 your-command-here
Example Use Case For 'stdbuf' Command
Here, I have a C program in the file 'calm-down.c' that prints out a message to help people who have anxiety disorders:
#include <unistd.h>
#include <stdio.h>
int main(){
while(1){
printf(
"\033[93mURGENT WARNING\033[0m: "
"'\033[31;4mEVERYTHING IS FINE!!!\033[0m'\033[B\r"
);
usleep(500000);
}
}
If I compile and run this program like this:
gcc calm-down.c -o calm-down
./calm-down
I don't see any output, even though my 'printf' statement will obviously run at least once.
If I pipe the output of this program into the 'xxd' command like this:
./calm-down | xxd
I still don't see any output! What's going on? I'm starting to feel stressed out!
It turns out that, by default, many programs that output to an interactive terminal use line based output buffering Since the text in this program doesn't contain any newlines, the output simply accumulates in the buffer without showing up in the terminal.
I can use this 'stdbuf' command to run my program with line based output buffering switched off:
stdbuf -o0 ./calm-down
Now, when I run my program, I can see my helpful message:
After reading the above message, all of my fears have now gone away!
Other Buffer Control Options
The 'stdbuf' command includes even more buffering options for input and error streams. It also allows you to control the buffers size, and explicitly switch to line-based buffering. See the 'man' and 'info' pages for more information:
info stdbuf
man stdbuf
And that's why the 'stdbuf' command is my favourite Linux command.
Intro To 'stty' Command In Linux
Published 2023-10-04 |
$1.00 CAD |
Intro To 'nproc' Command In Linux
Published 2023-07-15 |
Intro To 'comm' Command In Linux
Published 2023-09-06 |
How To Force The 'true' Command To Return 'false'
Published 2023-07-09 |
A Surprisingly Common Mistake Involving Wildcards & The Find Command
Published 2020-01-21 |
A Guide to Recording 660FPS Video On A $6 Raspberry Pi Camera
Published 2019-08-01 |
Intro To 'chroot' Command In Linux
Published 2023-06-23 |
Join My Mailing List Privacy Policy |
Why Bother Subscribing?
|