Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How redirection internally works in unix

Lets take an example : i have an executable named a.out. This contains binary information to print some text to STDOUT cos of printf. So when I give ./a.out, i see output of printf at the console STDOUT

Say if i do './a.out > tempFile' in console. How does this work? Since there is printf inside a.out, ideally i except the text to be printed in STDOUT. How does redirection consume this text and why do we not see any output in console and only in the file we see the printf text

like image 255
purvaja10 Avatar asked Oct 26 '25 00:10

purvaja10


2 Answers

In UNIX, everything is a file. All stdout is by default is the (for example) /dev/tty file which is a device driver hooked up to your console/terminal/window. Output is just sent to that file (device driver) which causes it to be output to whatever you're using for interactive I/O.

All the a command like a.out >xyzzy.txt does is first connect the standard output of the program to that file rather than /dev/tty, hence the output shows up there instead.

like image 108
paxdiablo Avatar answered Oct 29 '25 13:10

paxdiablo


in unix, everything is a file / filestream

a unix process has got 3 file streams connected by default:

0 = stdin
1 = stdout
2 = stderr

"normally", stdin is connected to the terminal emulation which will parse your keyboard input and stdout/stderr is connected to the terminal emulation that will provide your display.

the terminal emulator might be an xterm, gnome-terminal, kterm , or the linux virtual console ("textmode-console")

when you redirect, the stream is simply connected to a different source/destination. SO every text that would have gone to the terminal emulation will go to the file instead.

If you want both, "tee" might be an option:

./a.out | tee tempFile   

will print it out to the stdout (of tee, which you might redirect again) AND write it to the tempFile

like image 38
DThought Avatar answered Oct 29 '25 14:10

DThought