LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   why does this work? (https://www.linuxquestions.org/questions/programming-9/why-does-this-work-377410/)

Thinking 10-27-2005 10:03 AM

why does this work?
 
hiho@ll

excuse for the generalized subject, but i was to uncreative to post it in another way

well my "problem":

i have this code:

Code:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(){
 close(2);
 printf("TEST");
}

which gets executed this way:
Code:

g++ -o descr.o descr.test.c
./descr.o 2>err.out 1>&2

what does this do?

in the prog itself i only close stderr (2) and write the String TEST to stdout (1)
the commandline redirects
stderr to a file err.out
and
stdout to stderr

what i'm asking myself now is
why does this work?
if i do a
cat err.out

i get
TEST

this means that printf("TEST"); has been written to err.out through stderr, which i closed at the begining of the prog!?

thx@ll

rstewart 10-27-2005 10:28 AM

Hi,

I believe it works because of the following:

1) Shell redirects stderr to err.out
2) Shell closes generic stdout file descriptor, dups current stderr file descriptor and assigns it to stdout

Now when your program begins you still have two different file descriptors, one for stdout and one for stderr and they are both pointing to err.out

3) Your program closes file descriptor for stderr, however stdout file descriptor is still fully functional
4) You program writes text to stdout, since it was going to file err.out the text is placed into the file.

The points to note are that the shell does not point stdout to stderr's file descriptor, it duplicates it thus creating a valid and autonomous new file descriptor for stdout. When you close stderr, you are only closing one instance of the access to your err.out file.

I hope that my explanation is clear enough.

Thinking 10-27-2005 10:39 AM

sounds very good!

thx


All times are GMT -5. The time now is 04:55 PM.