Issue
I did some test with cat and redirection and there are some behaviors I do not understand.
I understand that when you cat /dev/stdout
or /dev/stderr
, it tells cat to read from terminal(like cat without arguments).
But why when I do
cat /dev/stdout > file.txt
I got a permission denied: cat: /dev/stdout: Permission denied
(for me it should behave like cat /dev/stdout
with no redirections and output to the file.txt) but when I do:
cat /dev/stderr > file.txt
what is written goes well to file.txt, it must not no ? And also why
cat /dev/stderr 2> file.txt
does nothing ? But
cat /dev/stderr 2>&2 > file.txt
redirect well to file.txt.
I just wanna know why it behave like that in those cases. Thanks.
Solution
Its an order of operations effect.
The shell redirections happen in the shell as it is setting up the environment to exec the command. /dev/stdout
however is just a filename (string) that is passed as an argument to to command and not processed by the shell at all.
So when you run cat /dev/stdout > file.txt
the shell first opens file.txt for writing, then changes stdout to refer to that file descriptor, then runs the cat
program with /dev/stdout
as an argument.
The cat
program then tries to open /dev/stdout
for reading.
Now /dev/stdout
isn't a real file -- its generally just a symlink to /dev/fd/1
, which is either a device special file, or something on custom dev filesystem, so opening involves calling a special routine in the device driver which tries to dup the stdout filedescriptor as a new file descriptor with read privledges. The problem is that stdout is a file descriptor referring to file.txt with write privedges, but no read privledges, so you get a "Permission Denied".
Answered By - Chris Dodd Answer Checked By - Willingham (WPSolving Volunteer)