How redirection internally works in unix

。_饼干妹妹 提交于 2020-01-05 00:47:39

问题


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


回答1:


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.




回答2:


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




回答3:


The shell executes a.out and replaces stdout with the file tempFile. There are a few functions (dup2, fropen) one can use to do this depending on the sort of redirection you want to achieve.:

See here: Redirecting the output of a child process




回答4:


Redirection is be a separate process which does the linking of the standard output of a.out to tempFile instead of /dev/tty(driver for printing to your terminal). So you see the output only in file and not in your console. This should be done before a.out executes. Once the linking is done by redirection operator , your execution of a.out starts and ends up printing in file.



来源:https://stackoverflow.com/questions/12812579/how-redirection-internally-works-in-unix

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!