Home >Backend Development >Golang >How to make the output (stdout, stderr) of any shell command unbuffered?

How to make the output (stdout, stderr) of any shell command unbuffered?

王林
王林forward
2024-02-06 09:12:101299browse

如何使任何 shell 命令的输出(stdout、stderr)不缓冲?

Question content

Is there a way to run a shell command without output buffering?

For example, hexdump file | ./my_script will only pass the input from hexdump to my_script in buffered chunks, not line by line.

What is the general solution to make the output of any command unbuffered?


Correct answer


As far as I know, you can't do this without ugly hacks. Writing to a pipe (or reading from a pipe) automatically turns on full buffering, there's nothing you can do about it :-(. "Line buffering" (which is what you want) is only used when reading/writing to the terminal. Ugly hack Exactly what this does: they connect the program to a pseudo-terminal so that other tools in the pipeline read/write from that terminal in line-buffered mode. The entire problem is described as follows:

The page also provides some suggestions (the "ugly hack" mentioned earlier), i.e. using unbuffer or doing some tricks with LD_PRELOAD.

The above is the detailed content of How to make the output (stdout, stderr) of any shell command unbuffered?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete