How to tail stdout or any of the standard streams?
Each process has its own stdout. So you need to capture the standard output of some running process. The usual way is to make a pipeline, but you may also redirect the stdout to some file.
Learn more about tee(1). Read some bash scripting tutorial
A typical use might be thru batch(1) and a here document; I often do
batch << EOJ
make >& _make.out
EOJ
the >&
is a bash-ism or a zsh-ism redirecting both stdout and stderr.
Then in a separate terminal -or even in the same terminal, after the batch
sequence above- (in the same current directory)
tail -f _make.out
This enables me to see the progression of e.g. a long-lasting compilation (of course I can interrupt with Ctrl C the tail -f
command without harming the compilation). YMMV.
Read also advanced bash scripting guide
Actually, /dev/stdout
(notice that stdout
alone means nothing particular to the shell) is a symlink to /proc/self/fd/1
. Read proc(5)
BTW, in your C code, take the habit of calling fflush(3) before any important syscall like sleep
or fork
(your code don't need it because stdout on terminal is line buffered but might be differently buffered when stdout is not a tty). Read stdout(3). Terminals are weird beasts, read tty demystified
addenda
To test in your C or C++ code if stdout
is a terminal, use isatty(3), i.e.
if (isatty(STDOUT_FILENO))
stdout_is_a_terminal();
Notice that stdout could be a pipe or a file (then of course the above test would fail).
To write to the terminal, use /dev/tty
(see tty(4)). To write on the console use /dev/console
(see console(4)...). For system logging, learn about syslog(3) and e.g. rsyslogd(8).
Related videos on Youtube
ewolfers
Updated on June 13, 2022Comments
-
ewolfers almost 2 years
I'm trying to understand how standard streams work in Linux, specifically how I can capture say,
stdout
directly from my terminal with something like tail. Since everything in Linux is a file, isn't it possible to simply do atail -f /dev/stdout
?So to test this, I wrote a trivial program:
int main(int argc, char * argv[]) { while (1) { printf("This takes advantage of stdout\n"); sleep(1); } return 0; }
Then in a separate terminal I did a
tail -f stdout
, but nothing is printed. Am I doing something wrong?-
Sergey L. almost 10 yearsHave you tried
./yourprogram | tail -f
? -
pmg almost 10 years
stdout
is like a virtual file. It only exists internally inside your program; other (C) programs (maybe running at the same time) have a differentstdout
. -
n. m.Stdout of which program did you hope to capture this way? There are many processes running and a Linux box is not an expert mind reader to know exactly which one you wanted. Perhaps a Mac OS X box would do a better job...
-