redirection vs pipe - why it works and why it doesn't

611 Views Asked by At

I have an encrypt() function that goes like this:

encrypt -a aes -k key **-i input.file** -o output.file

which take in 1 input file and output 1 file as well.

By using pipe:

echo "abc" | encrypt -a aes -k key -o output.file

Q1) How does the encrypt() function know or the OS know that the output for the pipe | is suppose to be the input for the encrypt function (so that i didn't need to specify the "-i input.file" parameter) ?

Q2 Why does redirection works in this case ? echo "abc" > encrypt -a aes -k key -o output.file

2

There are 2 best solutions below

11
On BEST ANSWER

When you use a pipe, conventional files are not involved. When you invoke

echo "abc" | encrypt -a aes -k key -o output.file

the encrypt program does not open a file at all, instead it reads its standard input. The standard input is whatever you set up on the command line when you invoked it. Standard input can be a pipe, as in your example. If you use input redirection, standard input can be a file:

encrypt -a aes -k key -o output.file < otherinput.file

Finally, if you don't use any pipes or input redirection at all, that is, if you invoke

encrypt -a aes -k key -o output.file

then the encrypt program will read from the keyboard.

Your second question Q2 is meaningless, though. You will end up creating an output file named "encrypt", and you won't run the encrypt program at all. If you want to use output redirection to control where the encrypt program's output goes, you could use

encrypt -a aes -k key -i input.file > output.file

or

echo "abc" | encrypt -a aes -k key > output.file
4
On

When you type echo abc | encrypt ..., the shell reads the entire string and parses it. It executes echo with its stdin set to the stdin of the current shell and its stdout set to the write end of a newly created pipe. It also forks a copy of encrypt and sets its stdin to the read side of that pipe and sets its stdout to the stdout of the shell. (Note that assigning the stdin of echo is a no-op and nothing is actually done, since the stream is simply inherited from the shell. It is also ignored by echo, and if this is confusing please ignore this parenthetical statement.) The OS knows about these associations only in the sense that the internal data structures for each process keep track of the open file descriptors. In other words, the shell is doing all the work.

Addressing the second question: "Why does redirection works[sic] in this case?", I wonder what you mean when you say it works. echo "abc" > encrypt -a aes -k key -o output.file is exactly equvialent to echo abc -a aes -k key -o output.file > encrypt, so one would expect the output of echo to be written to a file named encrypt, but the encrypt command is not executed.