purvaja10
purvaja10

Reputation: 41

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

Upvotes: 3

Views: 844

Answers (4)

user982845
user982845

Reputation: 29

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.

Upvotes: 0

sashang
sashang

Reputation: 12214

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

Upvotes: 0

DThought
DThought

Reputation: 1314

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

Upvotes: 2

paxdiablo
paxdiablo

Reputation: 882048

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.

Upvotes: 3

Related Questions